Search code examples
c#dependency-injectionunity-container

Created nested lifetime scope with Unity DI


I have a Web API project that uses Unity as the GlobalConfiguration.Configuration.DependencyResolver. The project uses the Unit of work pattern with a single data access layer that is kept in-memory throughout the lifetime of each request. At the end of each request events are fired, I want to execute the events using their own unique data access layer so that they can be run in parallel (sharing causes concurrency issues).

How can I create a child lifetime scope within a Http request context?

I have access to a static instance of UnityDependencyResolver which has the method IDependencyScope BeginScope(), but given it implements System.Web.Http.Dependencies.IDependencyResolver it seems using that is not the correct option?

With other DI frameworks such as Autofac, it would be:

using(var scope = container.BeginLifetimeScope())
{
  var service = scope.Resolve<IService>();

  using(var nestedScope = scope.BeginLifetimeScope())
  {
    var anotherService = nestedScope.Resolve<IOther>();
  }
}

I would prefer to move the events to a different process and fire via message queues but it is not possible at this time.


Solution

  • Unity container can create child container:

    using(var scope = container.CreateChildContainer())
    {
      var service = scope.Resolve<IService>();
    
      using(var nestedScope = scope.CreateChildContainer())
      {
        var anotherService = nestedScope.Resolve<IOther>();
      }
    }
    

    Combine it with different lifetime managers (HierarchicalLifetimeManager for example) and you can your result.