I have ASP.NET MVC application. It was using .NET 4.5.1 with below Unity versions
<package id="Unity" version="4.0.1" targetFramework="net451" />
<package id="Unity.Mvc" version="4.0.1" targetFramework="net451" />
This is how i was registering 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;
}
this has been working fine.
Now i updated .NET Framework to 4.6.2 and also Unity versions to
<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" />
However doing so throws exception on application startup during the DBContext registration
Registration where both MappedToType and InjectionFactory are set is not supported
答案 0 :(得分:9)
使用InjectionFactory时,不应将显式类型设置为在RegisterType
中实例化。
这应该有效:
container.RegisterType<DbContext>(new PerRequestLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
您将实例化对象的作业委托给自定义工厂,因此容器不需要知道要实例化的类型。