0

我有一个类,我在其中注入两个服务依赖项。我正在使用 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 容器实现它?

4

1 回答 1

0

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

// ... 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 ...
    }
}
于 2021-02-27T10:07:22.623 回答