Registration where both MappedToType and InjectionFactory are set is not supported
Asked Answered
T

1

9

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

Trilogy answered 18/4, 2018 at 18:7 Comment(0)
B
13

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.

Benildis answered 19/4, 2018 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.