Search code examples
c#asp.netasp.net-web-apidependency-injectionunity-container

Unity DI: Resolving from per-request to global singleton to per-request


I have a controller calling a global singleton calling a per-request-instance in the context of a ASP.NET WebAPI. Basically

per-request => singleton => per-request

Is the below setup correct? I'm particularly worried about the second per-request instance, since it could be user-based claims.

Or is that an anti-pattern and the singleton should receive (per-request) dependencies from the controller?

    // UnityConfig.cs, the Resolver uses CreateChildContainer()
    public static void RegisterTypes(IUnityContainer unity)
    {
        // global singleton
        unity.RegisterType<MessageContext>(new ContainerControlledLifetimeManager());
        // instance per request
        unity.RegisterType<ClaimsContext>(new HierarchicalLifetimeManager());
    }

    // API controller
    public class MyController : ApiController
    {
        private readonly MessageContext _message;

        public FormController(MessageContext message)
        {
            _message = message;
        }

        public Task<IHttpActionResult> MyAction()
        {
            _message.FireAndForget();
            return Ok();
        }
    }

    // global singleton to keep connection pool
    public class MessageContext
    {
        private readonly IUnityContainer _unity;

        public MessageContext(IUnityContainer unity)
        {
            _unity = unity;
        }

        public Task FireAndForget()
        {
            // resolve per request
            var claim = _unity.Resolve<ClaimsContext>().MyClaim);
            // ...
        }
    }

Solution

  • As pointed out in the comments, above sample code needs to be restructured. To fix, I split MessageContext into a long-lived and a short-lived part. The short-lived part receives the short-lived ClaimsContext, while the long-lived part only holds onto long-lived connections.