c# - Transient 注入(inject) Singleton 有什么问题?

标签 c# .net dependency-injection simple-injector di-containers

存在名为 Captive Dependency 的 DI 容器配置不正确的问题由马克西曼。 很明显,例如,将“PerCall”依赖项注入(inject)到“单例”依赖项中。但是如果将“ transient ”注入(inject)到“单例”中,情况会怎样呢?我不太明白为什么我不应该在某些情况下特别这样做,例如注册为瞬时注入(inject)到单例服务中并永远存在的计时器。

存在生活方式不匹配 diagnostic warning在 SimpleInjector DI 容器中。描述说:

it is safe for a transient component to depend on a singleton, but not the other way around

为什么不好?在这种情况下,坏事的一个很好的例子将非常有用。 当它“总是”不好或可以允许某些情况时是否有任何限制(参见我上面的示例)?

最佳答案

这取决于您如何定义“ transient ”的含义。 Simple Injector 文档,例如,states :

Simple Injector considers Transient registrations to be lasting for only a short time; temporary, i.e. short lived and not reused. For that reason, Simple Injector prevents the injection of Transient components into Singleton consumers as they are expected to be longer lived, which would otherwise result in Lifestyle Mismatches.

但其他 DI 容器对“ transient ”使用不同的定义。例如,.NET Core DI 容器 (MS.DI) 建议您的临时注册为“lightweight, stateless services.

因为它们被假定为无状态的,所以将它们注入(inject)到具有任何其他生命周期的消费者中是安全的,只要它们自己没有任何有状态(子)依赖项。在 MS.DI 的上下文中,“有状态”通常表示范围内的依赖项。 MS.DI 对 transient 的定义与 Autofac 所称的 Instance Per Dependency 相同。 IMO,Autofac 的命名更正确,因为从概念上讲,transient 的两种定义有很大区别,我相信大多数 DI Container 都遵循“只持续很短的时间;临时的”定义。

只要您的 Transient 组件无状态并且只要该组件不包含有状态的依赖项,将其注入(inject)单例(或作用域)消费者就没有坏处。然而,将这种无状态组件注入(inject)到单例中,仍然会使该组件长寿,这与短命完全不同。由于 Simple Injector 不知道您的组件是否包含状态,它认为所有瞬变都是短暂的,因此会警告您将瞬变注入(inject)单例。

关于c# - Transient 注入(inject) Singleton 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56289997/

相关文章:

c# - 我应该默认推荐密封类吗?

c# - 在现有项目上创建 View 模型

c# - 通过 IP 阻止连接

c# - 读取新闻文章实际内容并忽略页面上的 "noise"的算法?

oop - 依赖注入(inject)容器 - 工厂模式

dependency-injection - 验证我了解 IoC、Ioc 容器、DI 和服务定位器之间的区别

c# - 我的文档类应该有打印方法还是应该有一个专用的打印机类?

.net - DbContext ChangeTracker : Id of Added Entity for Auditing

javascript - 使用函数柯里化(Currying)在 typescript 中构建实用程序类

c# - N 层应用程序身份验证(RabbitMQ 作为代理,C# 作为业务层)- WIF 可能吗?