不支持同时设置 MappedToType 和 InjectionFactory 的注册
Registration where both MappedToType and InjectionFactory are set is not supported
我有 ASP.NET MVC 应用程序。它使用低于 Unity 版本的 .NET 4.5.1
<package id="Unity" version="4.0.1" targetFramework="net451" />
<package id="Unity.Mvc" version="4.0.1" targetFramework="net451" />
这就是我注册 DBContext 的方式
container.RegisterType<DbContext, MyDBContext>(new PerRequestLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
private static MyDbContext CreateDBContext()
{
MyDbContext dbContext = new MyDbContext ();
dbContext.Configuration.LazyLoadingEnabled = false;// turn-off loading on-demand
dbContext.Configuration.ProxyCreationEnabled = false;// turn-off dynamic proxy class generation
return dbContext;
}
这一直运行良好。
现在我将 .NET Framework 更新为 4.6.2,并将 Unity 版本更新为
<package id="Unity" version="5.8.5" targetFramework="net462" />
<package id="Unity.Abstractions" version="3.3.0" targetFramework="net462" />
<package id="Unity.Container" version="5.8.5" targetFramework="net462" />
<package id="Unity.Mvc" version="5.0.13" targetFramework="net462" />
但是这样做会在 DBContext 注册期间在应用程序启动时抛出异常
Registration where both MappedToType and InjectionFactory are set is
not supported
使用 InjectionFactory 时,不应在 RegisterType
中设置要实例化的显式类型。
这应该有效:
container.RegisterType<DbContext>(new PerRequestLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
您将实例化对象的工作委托给自定义工厂,因此容器不需要知道要实例化的类型。
我有 ASP.NET MVC 应用程序。它使用低于 Unity 版本的 .NET 4.5.1
<package id="Unity" version="4.0.1" targetFramework="net451" />
<package id="Unity.Mvc" version="4.0.1" targetFramework="net451" />
这就是我注册 DBContext 的方式
container.RegisterType<DbContext, MyDBContext>(new PerRequestLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
private static MyDbContext CreateDBContext()
{
MyDbContext dbContext = new MyDbContext ();
dbContext.Configuration.LazyLoadingEnabled = false;// turn-off loading on-demand
dbContext.Configuration.ProxyCreationEnabled = false;// turn-off dynamic proxy class generation
return dbContext;
}
这一直运行良好。
现在我将 .NET Framework 更新为 4.6.2,并将 Unity 版本更新为
<package id="Unity" version="5.8.5" targetFramework="net462" />
<package id="Unity.Abstractions" version="3.3.0" targetFramework="net462" />
<package id="Unity.Container" version="5.8.5" targetFramework="net462" />
<package id="Unity.Mvc" version="5.0.13" targetFramework="net462" />
但是这样做会在 DBContext 注册期间在应用程序启动时抛出异常
Registration where both MappedToType and InjectionFactory are set is not supported
使用 InjectionFactory 时,不应在 RegisterType
中设置要实例化的显式类型。
这应该有效:
container.RegisterType<DbContext>(new PerRequestLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
您将实例化对象的工作委托给自定义工厂,因此容器不需要知道要实例化的类型。