我有一个类,我在其中注入了两个服务依赖项。我正在使用 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());
}
}
这个泛型类总是重新调整null懒惰的值。
我从我的服务类调用这个方法,如:-
LazyInitialization<AClass>.LazyDefault.Create<AClass>();
如何使用 Unity 容器实现它?
答案 0 :(得分: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 ...
}
}