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
When using an InjectionFactory, you should not set the explicit type to instantiate in RegisterType
.
This should work:
container.RegisterType<DbContext>(new PerRequestLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
You are delegating the job of instantiating the object to a custom factory, therefore the container does not need to know the type to instantiate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With