无法向 Unity 和 Entity Framework 注册 DbConnection

Unable to register DbConnection with Unity and Entity Framework

我完全不确定导致此异常的根本问题是什么。

我正在使用 ASP.NET MVC,Unity.Mvc 和 Entity Framework 6. 我有以下代码来注册我的存储库:

    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your types here
        // container.RegisterType<IProductRepository, ProductRepository>();

        container.RegisterType<IGenericRepository<Customer>, GenericRepository<Customer>>();
        container.RegisterType<IGenericRepository<Product>, GenericRepository<Product>>();
        container.RegisterType<IGenericRepository<Order>, GenericRepository<Order>>();
        container.RegisterType<IGenericRepository<OrderItem>, GenericRepository<OrderItem>>();
        container.RegisterType<IGenericRepository<Supplier>, GenericRepository<Supplier>>();
    }

然后在控制器中我有:

public class IndexController : Controller
{
    public IndexController(IGenericRepository<Customer> testGenericRepository)
    {
        var result = testGenericRepository.SelectAll();
    }

    public ActionResult Index()
    {
        return View();
    }
}

并且存储库具有以下代码:

public class GenericRepository<T> : IGenericRepository<T>
        where T : class
    {
        private readonly DbContext _dbContext;
        private readonly IDbSet<T> _dbSet;

        public GenericRepository(DbContext dbContext)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            _dbContext = dbContext;
            _dbSet = _dbContext.Set<T>();
        }

        public IEnumerable<T> SelectAll()
        {
            return _dbSet.AsEnumerable<T>();
        }
    }

我遇到的问题是,如果我在 "RegisterTypes" 方法中有一个断点,我可以看到容器肯定会注册所有存储库,但在构造函数中有一个断点存储库永远不会受到攻击。

所以我认为断点没有命中,而且我没有注册 "System.Data.Common.DbConnection" 意味着存储库使用的 DbContext 永远不会设置。

我找不到任何有关如何将 "System.Data.Common.DbConnection" 与 Unity 和 Entity Framework 中的 DbContext 一起使用的有用信息。

我该如何解决这个问题?

您应该在 RegisterTypes 中添加如何构建您的 DbContext,以及可能的生命周期。

如果您有自己的 class(比如 CustomContext)继承自 DbContext,请注册它。假设您的默认生命周期足够:

container.RegisterType<DBContext, CustomContext>();

如果直接使用DbContext,指示Unity应该使用哪个构造函数。例如,假设您的连接字符串名为 appConnectionString:

container.RegisterType<DBContext>(
    new InjectionConstructor("name=appConnectionString"));