2016-08-11 55 views
0

我在我的ASP.NET MVC 4.6应用程序中使用Unity.MVC DI。我有一个服务接口传入控制器,这很好。现在我想传递一个接口到EF上下文到服务,但我不知道如何做到这一点。我读过EF有这个IObjectContextAdapter,我可以将它传递到我的服务ctor中,但是我需要从这个上下文中查询我的服务中的实际表,但是因为它是一个IObjectContextAdapter,它不知道我的表。我该怎么做呢?ASP.NET Unity.MVC DI与EF上下文

public class ContactService : IContactService 
    { 
     //private ContactsEntities context; 
     private IObjectContextAdapter context; 

     // test ctor 
     public ContactService(IObjectContextAdapter ctx) 
     { 
      context = ctx; 
     } 

     // prod ctor 
     public ContactService() 
     { 
      context = new ContactsEntities(); 
     } 

     List<Contact> GetAllContacts() 
     { 
      return (from c in context.ObjectContext.?? // I need to query the Contacts table that would be attached to the actual context I pass in but still keep the decoupling from using an Interface passed into the ctor 

     } 
    } 

回答

1

IObjectContextAdapter的是DbContextObjectContext属性的类型。

您应该子类DbContext例如ContactsDatabaseContext

public class ContactsDatabaseContext : DbContext, IContactsDatabaseContext 
{ 
    // ... 
} 

然后就是你的ContactsDatabaseContext与IoC容器注册。事情是这样的:

container.RegisterType<IContactsDatabaseContext, ContactsDatabaseContext>(); 

ContactsDatabaseContextIContactsDatabaseContext接口应具有引用您的表DbSet<T>类型的属性,例如:

IDbSet<BrandDb> Users { get; set; } 

UPDATE:

由于您使用的是生成的文件,那就这样做:

public partial class ContactsDatabaseContext : IContactsDatabaseContext 
{ 
    // Expose the DbSets you want to use in your services 
} 
+0

我是先做数据库,然后触摸自动生成的ContactContext文件是不行的?由于它是自动生成的。 – user441521

+0

自从我上次使用EF生成的文件已经很长时间了,但这意味着您已经是该课程了。那很好。您现在可以注册它。如果你想要的话,你仍然可以添加接口(如果不是已经存在的话,用partial关键字声明类并分配接口。这样,你就不必改变生成的代码了(这就是部分原因) –

+0

@ user441521,看看更新是否有帮助 –