简体   繁体   English

Unity DI:从每个请求到全局单例再到每个请求

[英]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. 我有一个控制器在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);
            // ...
        }
    }

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. 为了解决此问题,我将MessageContext分为了长期和短期两个部分。 The short-lived part receives the short-lived ClaimsContext , while the long-lived part only holds onto long-lived connections. 短命的部分接收短命的ClaimsContext ,而长命的部分仅保留长命的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM