ASP.NET Unity.MVC 带有 EF 上下文的 DI

ASP.NET Unity.MVC DI with EF context

我在 ASP.NET MVC 4.6 应用程序中使用 Unity.MVC 作为 DI。我有一个服务接口传递到控制器,它工作得很好。现在我想将 EF 上下文的接口传递给服务,但我不确定如何执行此操作。我读过 EF 有这个 IObjectContextAdapter,我可以将它传递到我的服务构造函数中,它可以工作,但是我需要从这个上下文中查询我的服务内部的实际表,但是因为它是一个 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

        }
    }

IObjectContextAdapterDbContextObjectContext 属性 的类型。

你应该subclass DbContext 例如ContactsDatabaseContext

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

然后只需在 IoC 容器中注册 ContactsDatabaseContext。像这样:

container.RegisterType<IContactsDatabaseContext, ContactsDatabaseContext>();

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

IDbSet<BrandDb> Users { get; set; }

更新:

既然你使用的是生成的文件,那么就这样做:

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