【问题标题】:Unity lazy resolveunity懒解决
【发布时间】:2012-04-05 09:29:15
【问题描述】:

我有 MVC webApiUnity 一起使用的应用程序。我必须将接口ITest 解析为单例类(DelegateHandler)。但是接口 ITest 具有每个httprequest 生命周期管理器,这很重要。所以我无法解决 Application_Start 事件上的 ITest 因为现在没有 HttpRequest 但 DelegateHandler 只会在 httprequest 生命周期中使用 ITest。

那么是否可以向 DelegateHandler 发送惰性解析,或者也许有人有其他有趣的解决方案?

【问题讨论】:

    标签: .net dependency-injection unity-container ioc-container lazy-evaluation


    【解决方案1】:

    服务的生命周期应始终等于或短于其依赖项的生命周期,因此您通常会将 ITest 注册为 Per Http Request 或 Transient,但如果这不可能,请包装依赖项(DelegateHandler 我假设) 在代理中具有每个 Http 请求的生命周期:

    // Proxy
    public class DelegateHandlerProxy : IDelegateHandler
    {
        public Container Container { get; set; }
    
        // IDelegateHandler implementation
        void IDelegateHandler.Handle()
        {
            // Forward to the real thing by resolving it on each call.
            this.Container.Resolve<RealDelegateHandler>().Handle();
        }
    }
    
    // Registration
    container.Register<IDelegateHandler>(new InjectionFactory(
        c => new DelegateHandlerProxy { Container = c }));
    

    【讨论】:

    • 将其转换为通用解决方案会很酷,但可能是不可能的)
    【解决方案2】:

    另一种选择是执行以下操作:

    public class Foo
    {
        Func<IEnumerable<ITest>> _resolutionFunc;
        ITest _test;
        public Foo(Func<IEnumerable<ITest>> resolutionFunc)
        {
            _resolutionFunc=resolutionFunc;
        }
    
    private void ResolveFuncToInstance()
    {
        _test=_resolutionFunc().First();
    }
    }
    

    我们正在做的是要求 Unity 为我们提供一个委托,该委托将解析容器中的所有 ITest 实例。由于这是一个 Func,我们可以在想要从 Unity 进行实际解析时调用它。

    这与 Steven 所做的事情大致相同,但使用内置的 Unity 功能来完成我们正在寻找的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多