.Net 核心 DI 范围验证,范围与瞬态? [英] .Net core DI Scope validation , scoped vs transient?

查看:22
本文介绍了.Net 核心 DI 范围验证,范围与瞬态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读文档 :

当应用在开发环境中运行时,默认服务提供商执行检查以验证:

When the app is running in the Development environment, the default service provider performs checks to verify that:

  • 范围服务不是从根服务提供者直接或间接解析的.
  • 范围服务不会直接或间接注入单身人士

这意味着我不应该将 Scoped 服务注入到单例服务中.

This means that I shouldn't inject Scoped services into a singleton service.

基于瞬态服务在每次请求时都会创建一个实例的事实,VS 范围内的服务在整个请求的生命周期中都是单个实例:

Based on the fact that transient services creates an instance each time they're requested, VS scoped services which are single instances throughout the request's lifecycle :

问题:

为什么 DI 只验证范围服务而不验证瞬态服务?

Why does the DI only validate scoped services and not also transient services?

推荐答案

从单例解析范围服务是危险的.可能导致服务在处理后续请求时状态不正确.

It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.

来自文档 以上描述了他们为什么要进行此项检查.为了更好地理解这一点,我开始阅读有关各种生命周期的内容,我自己更像是一个 autofac 人,以了解注册的 .net 核心风格.

From the Docs the above describes why they do this check. To understand this better I started reading about the various lifetimes more being an autofac guy myself to understand the .net core flavor of registrations.

  • 范围注册需要一个服务生命周期每个请求的实例(连接)
  • Singleton 只有在注册时或构造函数运行时定义的单个状态.(在 startup.cs 中)
  • 瞬态是每个构造函数注入的一个新实例,即每个依赖.

通常,您会使用单例模式在您的应用程序生命周期等内存中维护某种状态,有很多用例,但重要的是要了解单例类的构造函数(在其中注入依赖项)将在整个应用程序生命周期内只运行一次.

Generally you would us the singleton pattern to maintain perhaps some sort state in memory for your application lifetime etc, there are many use cases but the important thing to understand that the constructor of your singleton class (where you inject your dependencies) will run once and only once for your entire application lifetime.

您可以想象,在不考虑上述情况的情况下将范围或瞬态服务注入单例会导致一些......意想不到的结果,您希望您的服务坚持其特定的生命周期,但实际上它真的只是由于单例的性质,每次都是同一个实例.

You could imagine that injecting a scoped or transient service into singleton while baring the above in mind will lead to some ... unexpected results , you are expecting your service to adhere to its specific life time but in actual fact its really just the same instance every time due to the nature of the singleton.

根据我的理解回答你的问题:注入到单例中的瞬态(虽然本质上不正确)仍然可以正常工作,因为它的生命周期很短并且几乎没有破坏状态的风险,而 scoped 保证单个请求的生命周期(以某种请求缓存为例),在被注入到单例中时,scoped 无法兑现那个生命周期.

To answer your question using my understanding : A transient injected into a singleton (while inherently not correct) will still function fine as its lifetime is short and runs of little risk of breaking state whereas scoped guarantees a lifetime across a single request (think some sort of request caching as an example), there is no way that scoped can honor that lifetime while being injected into a singleton.

这篇关于.Net 核心 DI 范围验证,范围与瞬态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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