我已经集成了我的项目snapp的统一容器,它有两个文件夹,名为Commerce和Order。我已经为Commerce文件夹中的类创建了构造函数依赖注入,比如它有控制器、管理器和存储类(manager & storage - singleton类)。商业文件夹中所有类的实例都已在统一容器中解析。
按照顺序,内部的文件夹类不遵循依赖注入模式,因此它们没有在统一容器中注册。
有几个问题-
发布于 2022-04-01 22:12:52
我认为有三种选择:
CommerceManager作为OrderManager构造函数的输入或类似的依赖注入(例如方法、倾向注入)。使用服务定位器模式的CommerceManager实例本身:如果CommerceManager是作为单个实例实现的,您可以直接访问实例,或者如果它不需要是单个实例,那么OrderManager可以实例化一个实例本身。好处是这很容易。然而,单元测试变得非常棘手,如果不是不可能的话,因为您不能模拟CommerceManager,因为OrderManager现在对它有一个硬编码的依赖。唯一可能的方法是将CommerceManager构建为一个真正的单例类(没有公共构造函数)。现在,听起来像是让DI容器控制类的生命周期。这意味着,只有当您通过DI容器访问CommerceManager实例时,才会使用单例实例。
如果其他项目是而不是通过DI容器访问它的,则需要通过类本身(或作为中间类的一些“访问器”类)来控制它:
public class SingletonCommerceManager
{
private static Lazy<SingletonCommerceManager> _instance
= new Lazy<SingletonCommerceManager>(() => new SingletonCommerceManager());
public static SingletonCommerceManager Instance => _instance.Value;
private SingletonCommerceManager()
{ /* ... */ }
}
// Or (essentially the same but removing "singleton logic" from CommerceManager)...
// 'internal' to only make it accessible within the assembly
internal class CommerceManager
{
internal CommerceManager()
{ /* ... */ }
}
// 'public' to make it the only way to access 'CommerceManager' outside the assembly
public class CommerceManagerAccessor
{
private Lazy<CommerceManager> _singletonInstance
= new Lazy<CommerceManager>(() => new SingletonCommerceManager());
public CommerceManager Singleton => _singletonInstance.Value;
}https://stackoverflow.com/questions/71711763
复制相似问题