c# - UnityContainer.Resolve 还是 ServiceLocator.GetInstance?

标签 c# dependency-injection inversion-of-control unity-container

这似乎是一个愚蠢的问题,因为在我的代码中一切正常,但我已经用我的 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/

相关文章:

c# - 仅适用于 SQL Server 兼容 C# 的解析时间(分钟 :Seconds. Ms)

c# - asp.net 核心构造函数注入(inject)继承

java - 在面向服务的架构中何时使用 Web api 而不是依赖注入(inject)

c# - 为 MVC 3 实现一点 IOC

gwt - 在 GWT 中处理 MVP 的 IoC/ "Springy"方式是什么? (提示,可能不是 Spring Roo 1.1 方式)

c# - 是否可以根据命名约定在 CaSTLe Windsor 中自动注册?

c# - WPF 中的运行与内容与文本

c# - 在 ASP.net 解决方案中使用 Unity IOC 容器

c# - 运行 Roslyn 脚本时在运行时找不到程序集

java - 相当于 Spring Boot 中用于动态注入(inject)的 javax.enterprise.inject.Instance