Search code examples
c#asp.net-web-apidependency-injectionasp.net-web-api2unity-container

Unity Container PerRequestLifetimeManager in Web Api


I have a WEB API application and I am using UnityContainer as my DI. Since I'm using UnitOfWork with Entity Framework I wanted to register the DataContext in the UnityContainer per each request. I was disappointed to find that no LifeTimeManager exists that can give me a new scope per request. After digging a little more, I found that Unity.AspNet.Mvc does contain a PerRequestLifetimeManager. My questions are:

  1. Is there a reason why Unity doesn't contain a PerRequestLifetimeManager? It seems to me that is a very common case to register something per request.
  2. Is there a particular reason why Unity.AspNet.Mvc does contain PerRequestLifetimeManager?
  3. Is there something I need to know if I am using Unity.AspNet.Mvc in a WebApi project?
  4. In case of using Thread or Tasks, how does the container knows it belongs to the same request?

Solution

    1. Is there a reason why Unity doesn't contain a PerRequestLifetimeManager? It seems to me that is a very common case to register something per request.

    The core library is for .Net projects. Only Asp.Net would have a Request.

    Is there a particular reason why Unity.AspNet.Mvc does contain PerRequestLifetimeManager?

    Same as answer 1. Requests are an Asp.Net concept.

    Is there something I need to know if I am using Unity.AspNet.Mvc in a WebApi project?

    Nope. You will most likely only be using the PerRequestLifetimeManager anyway. I would imagine the developers of Unity didn't see a need to publish a Mvc and a WebApi package when the two libraries would have been identical.

    In case of using Thread or Tasks, how does the container knows it belongs to the same request?

    The container is just another object. The .Net framework manages objects from request to request and thread to thread. The container itself creates a unique scope at the beginning of a request and destroys it at the end of the request .Net does everything in between.