c# – How to use single child Unity container for OWIN middleware and WebAPI

I am using OWIN to self host WebAPI service. There is Unity to serve as IoC container. Within several OWIN middlewares (e.g. authorization layer) as well as in WebAPI I need to access unity container to resolve my dependencies. There should be single child container per each request so that there is for example single DB context which is used several times during the request and it is disposed at the end of request along with unity container. For WebAPI I would like to use same container as for previous middlewares. However, default UnityHierarchicalDependencyResolver creates its own child container from given parent per each request. So that I had to write my own infrastructure to force WebAPI to use existing child container. Please review the following code snippets. I would be happy for any kind of feedback since this is quite critical part of my application.

Here is my app configuration method:

public static void Configure(IAppBuilder app, IUnityContainer container)
{
    //register middleware that creates child container for each request
    app.UseUnityContainer(container);

    //register other middlewares ...
    
    //create httpconfig
    var config = new HttpConfiguration
    {
        DependencyResolver = container.Resolve<OwinUnityDependencyResolver>()
    };

    //...

    config.MessageHandlers.Insert(0, container.Resolve<OwinDependencyScopeHandler>());

    app.UseWebApi(config);
}

This is UseUnityContainer extension method that is responsible for creating and disposing child containers:

public static void UseUnityContainer(this IAppBuilder app, IUnityContainer container)
{
    app.Use<UnityMiddleware>(container);
}

private class UnityMiddleware : OwinMiddleware
{
    private readonly IUnityContainer _parent;

    public UnityMiddleware(OwinMiddleware next, IUnityContainer parent) : base(next)
    {
        _parent = parent;
    }

    public override async Task Invoke(IOwinContext context)
    {
        using (var child = _parent.CreateChildContainer())
        {
            context.SetUnityContainer(child);
            await Next.Invoke(context);
        }
    }
}

To access and store container within the OWIN context there are following extension methods:

public static class UnityOwinContextExtensions
{
    private const string UnityContainerKey = "OwinUnityContainer";

    public static IUnityContainer GetUnityContainer(this IOwinContext context)
    {
        return context.Get<IUnityContainer>(UnityContainerKey);
    }

    public static void SetUnityContainer(this IOwinContext context, IUnityContainer container)
    {
        context.Set(UnityContainerKey, container);
    }
}

OwinUnityDependencyResolver class used in HttpConfiguration:

public class OwinUnityDependencyResolver : IDependencyResolver
{
    private static readonly IDependencyScope NullScope = new NullDependencyScope();

    private readonly IUnityContainer _parent;

    public OwinUnityDependencyResolver(IUnityContainer parent)
    {
        _parent = parent;
    }

    public void Dispose()
    {
        //parent container is disposed in SureStowWebApiService
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _parent.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _parent.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IDependencyScope BeginScope()
    {
        //BeginScope should not be called as there should be already scope registered by OwinDependencyScopeHandler
        return NullScope;
    }

    private class NullDependencyScope : IDependencyScope
    {
        public void Dispose()
        {
        }

        public object GetService(Type serviceType) => null;

        public IEnumerable<object> GetServices(Type serviceType) => null;
    }
}

OwinDependencyScopeHandler class that is used to retrieve existing child container from OWIN context and create new dependency scope out of it. This handler is registered in HttpConfiguration.

public class OwinDependencyScopeHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var context = request.GetOwinContext();
        var scope = new OwinUnityDependencyScope(context);

        //this prevents HttpRequestMessageExtensions.GetDependencyScope to initialize scope from dependency resolver
        request.Properties(HttpPropertyKeys.DependencyScope) = scope;

        return base.SendAsync(request, cancellationToken);
    }
    
    private class OwinUnityDependencyScope : IDependencyScope
    {
        private readonly IUnityContainer _container;

        public OwinUnityDependencyScope(IOwinContext owinContext)
        {
            _container = owinContext.GetUnityContainer(); //this is child container created by UnityMiddleware
        }
        
        public void Dispose()
        {
            //_container should be disposed by UnityMiddleware
        }

        public object GetService(Type serviceType) => _container.Resolve(serviceType);

        public IEnumerable<object> GetServices(Type serviceType) => _container.ResolveAll(serviceType);
    }
}