我在我的ASP.NET MVC4.6应用程序中使用了用于DI的Unity.MVC。我有一个传递给控制器的服务接口,它工作得很好。现在我想把EF上下文的一个接口传递给服务,但是我不确定该怎么做。我读到EF有这个IObjectContextAdapter,我可以将它传递给我的服务ctor,它可以工作,但是我需要从这个上下文中查询我的服务内部的实际表,但是因为它是一个IObjectContextAdapter,所以它不知道我的表。我该怎么做呢?
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
}
}发布于 2016-08-11 21:40:17
IObjectContextAdapter是DbContext的ObjectContext属性的类型。
你应该继承DbContext的子类,例如ContactsDatabaseContext
public class ContactsDatabaseContext : DbContext, IContactsDatabaseContext
{
// ...
}然后只需向IoC容器注册ContactsDatabaseContext即可。如下所示:
container.RegisterType<IContactsDatabaseContext, ContactsDatabaseContext>();您的ContactsDatabaseContext类和IContactsDatabaseContext接口应该具有引用您的表的DbSet<T>类型的属性,例如:
IDbSet<BrandDb> Users { get; set; }更新:
由于您使用的是生成的文件,因此请执行以下操作:
public partial class ContactsDatabaseContext : IContactsDatabaseContext
{
// Expose the DbSets you want to use in your services
}https://stackoverflow.com/questions/38897867
复制相似问题