Search code examples
asp.netentity-frameworkasp.net-web-apiasp.net-web-api2unity-container

Unity PerRequestLifetimeManager throwing exception in Web API app in RegisterTypes() method


I configured Unity in my Web API application to inject the dependencies, but it's throwing an exception when I try to register the DbContext with PerRequestLifetimeManager. It works fine if I use the default LifeTimeManager. I have Unity.MVC and Unity.Webapi nuget packages added to the app. Here is the code for RegisterTypes.

container                
.AddNewExtension<Interception>()                
.RegisterType(typeof(DbContext), typeof(MyDbContext), "MyContext", new PerRequestLifetimeManager())                
.RegisterType(typeof(IRepository<Country>), typeof(Repository<Country>), new InjectionConstructor(container.Resolve(typeof(DbContext),"MyContext")))                
.RegisterType(typeof(IRepository<Region>), typeof(Repository<Region>), new InjectionConstructor(container.Resolve(typeof(DbContext), "MyContext")))

It throws the following exception in RegisterTypes when I run the app.

Unity.Exceptions.ResolutionFailedException...

Inner Exception 1: InvalidOperationException: The PerRequestLifetimeManager can only be used in the context of an HTTP request.Possible causes for this error are using the lifetime manager on a non-ASP.NET application, or using it in a thread that is not associated with the appropriate synchronization context.

Any idea what I am doing wrong here?


Solution

  • I figured it out. Just like the error message says, I was trying to inject the DbContext in a non Http Request context at the time of application initialization. It works fine if I do it as shown below, without trying to configure the "InjectionConstructor" inside RegisterType for Repositories. It successfully injects a new instance of DbContext in the repository every request. Seems like you can't use InjectionConstructor for Types that are registered with "PerRequestLifetimeManager".

     container                
    .AddNewExtension<Interception>()                
    .RegisterType(typeof(DbContext), typeof(MyDbContext), "MyContext", new PerRequestLifetimeManager())                
    .RegisterType(typeof(IRepository<Country>), typeof(Repository<Country>))                
    .RegisterType(typeof(IRepository<Region>), typeof(Repository<Region>))