这似乎是一个愚蠢的问题,因为在我的代码中一切正常,但我已经用我的 Unity 容器 _ambientContainer
以这种方式注册了一个单例:
_ambientContainer.RegisterType<Application.StateContext>(new ContainerControlledLifetimeManager());
为了避免使用我的本地字段,我使用:
get {
return ServiceLocator.Current.GetInstance<Application.StateContext>();
}
在我的 get 属性中获取我的对象的一个实例。
这样我总是得到相同的实例(Application.StateContext
仍然是一个单例)或者 GetInstance
创建一个新实例?
使用本地 _ambientContainer
字段会更好吗?
get {
return _ambientContainer.Resolve<Application.StateContext>();
}
谢谢。
最佳答案
将容器的实例传递给消费者类通常不是一个好主意,因为您不再保证单个在您的应用程序中注册组件和服务的位置(已知作为 Composition Root )。
类应该在它们的公共(public) API 中声明它们的依赖关系,最好是 specifying them as constructor arguments ,容器将在被要求解析特定类型时自动提供实例(称为 Autowiring 的过程)。
Dependency Injection通常是 the preferred choice但它并不总是适用。在那些情况下使用 Service Locator ,就像您在示例中所做的那样,是 decouple a class from its dependencies 的下一个最佳解决方案.
总而言之,如果依赖注入(inject)不是一个选项,我会避免让我的类直接引用容器,而是让它们通过服务定位器访问它。
关于c# - UnityContainer.Resolve 还是 ServiceLocator.GetInstance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308424/