【发布时间】: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