【问题标题】:how can I Implement Lazy with Unity Dependency Injection如何使用 Unity 依赖注入实现 Lazy
【发布时间】:2021-02-27 08:44:59
【问题描述】:

我有一个类,我在其中注入两个服务依赖项。我正在使用 Unity 容器。

public UserService(ILazyInitialization<AClass> aCLass, ILazyInitialization<BClass> bClass) 
{ _aClass= aCLass; 
  _bClass= bClass; 
}

UnityCONfig 就像

 container.RegisterType<IAClass, AClass>(); 
 container.RegisterType<IBCLass, BClass>();

我创建了一个通用类来实现 Lazy

 public class LazyInitialization<T> : ILazyInitialization<T> where T : class 
    {
        private static Lazy<T> _lazy;
         

        public static class LazyDefault
        {
            static Type listType = typeof(T);
            public static Lazy<T> Create<T>() where T : new()
            {
                return new Lazy<T>(() => Activator.CreateInstance<T>());
                return  new Lazy<T>(() => new T());
            } 
        }

这个 Generic 类总是重新调整 null Lazy 的值。

我从我的服务类中调用此方法,例如:-

LazyInitialization<AClass>.LazyDefault.Create<AClass>();

如何使用 Unity 容器实现它?

【问题讨论】:

  • 欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 以了解如何提高问题的质量。然后edit你的问题包括你拥有的完整源代码作为minimal reproducible example,其他人可以编译和测试。目前尚不清楚您究竟在哪里获得 null 值以及何时/如何获得。

标签: c# unity-container lazy-initialization


【解决方案1】:

我不确定您的任务到底是什么,但是,如果您需要实例化对象而不是在解析阶段而是稍后手动说,您可以使用Lazy&lt;T&gt; 而不是ILazyInitialization&lt;T&gt;

// ... registration part ...
container.RegisterInstance<Lazy<IService>>(new Lazy<IService>(() => new Service()));

// another service
public class ServiceA : IServiceA
{
    private readonly Lazy<IService> _lazy;

    public ServiceA(Lazy<IService> lazyInstance)
    {
        _lazy = lazyInstance;
    }

    public void DoSmth()
    {
        // create instance
        var instance = _lazy.Value;
        // use instance below ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2015-10-25
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多