DI Singleton实例与瞬态实例 [英] DI Singleton instance vs Transient instance

查看:114
本文介绍了DI Singleton实例与瞬态实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几年前,IoC性能指南指出,应仅使用IoC容器解析长期存在的实例(基本上是单例),而应使用单例工厂(由容器保存)创建临时类型对象.

Several years ago IoC performance guidelines stated IoC containers should be used to resolve only long-lived instances (singletons basically), whereas transient type objects should be created using a singleton factory (held by the container).

我现在正在阅读有关ASP.NET Core的信息,我已经看到了几个示例,它们的注入对象都使用了Transient Lifetime.对于提供静态方法(无状态)的服务而言,暂时首选的方法是瞬态,现在已经改变了吗?

I am reading now about ASP.NET Core, and several examples I have seen use Transient lifetime for their injected objects. Has something changed where transient is now the preferred method for services that provide static methods (and are stateless)?

推荐答案

长期实例"的概念并没有说明其生命周期或生活方式,而是从消费者的角度出发,他们的一个实例.它们是无状态.

The notion of "long-lived instances" does not say anything about their lifetime or lifestyle per see, but rather that from perspective of the consumer, there is only one instance of them. They are stateless.

换句话说,长寿命实例"是指服务依赖项,而短寿命实例"是指以数据为中心的对象,例如实体,DTO,消息和视图模型.

In other words, "long-lived instances" refers to services or dependencies, while "short-lived instances" refers to data-centric objects, such as entities, DTOs, messages and view models.

这些服务由您的组合根(通常,但不一定是您的DI容器),而以数据为中心的对象则由应用程序代码直接管理.换句话说,那些长寿命的对象"是由合成根"更新"的,而短寿命的对象"是由应用程序代码本身更新的".

Those services are created and managed by your Composition Root (typically, but not nessicarily your DI Container), while data-centric objects are managed directly by application code. In other words, those "long-lived objects" are 'newed' up by the Composition Root, while "short-lived objects" are newed up by application code itself.

那些以数据为中心的对象是易失性的,它们通常只在请求期间(甚至更短)生存,尽管它们可能会被缓存并生存到应用程序寿命.

Those data-centric objects are volatile, they typically only live for the duration of the request (or even shorter), although they might be cached and live for as long as the application lives.

依赖也可以持续很短的时间,但是通常在请求的持续时间内.

Dependencies can as well live for a short duration, but typically for the duration of a request.

这篇关于DI Singleton实例与瞬态实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆