服务寿命瞬态,作用域,单例 [英] Service lifetimes transient vs scoped vs singleton

查看:167
本文介绍了服务寿命瞬态,作用域,单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在

https://docs .microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view = aspnetcore-2.1

并解释了asp.net核心DI和服务寿命.

and it explains a asp.net core DI and service lifetime.

文章提到了以下生命周期:

Article mentions following lifetimes:

  • 瞬变
  • 范围
  • 单人

我正在尝试找到一个真实的例子,或者至少是关于何时使用每个生命周期的更好解释.

I am trying to find a real world example or at least a better explanation on when to use each lifetime.

推荐答案

3个示例:

Singletons-这些可能存在于整个应用程序范围的配置设置中,例如,一个游戏管理器,它跟踪玩家在整个游戏中的进度.

Singletons - These may exist for the entire application wide configuration setting, for example a game manager that keeps track of players progress throughout the game.

作用域-建议对实体框架上下文进行作用域,以便您可以重用连接属性.

Scoped - entity framework contexts are recommended to be scoped so that you can reuse the connection properties.

瞬态-实体框架上下文不能由2个线程共享,因此如果您想进行任何异步工作.您将使用瞬态,以便为每个组件创建上下文的新实例.否则,您必须等待作用域组件完成才能移至下一个组件.

Transient - entity framework contexts can not be shared by 2 threads, so if you wanted to do any asynchronous work. You would use a transient so that a new instance of the context is created for every component. Otherwise you would have to wait for the scoped component to finish before it moves onto the next.

这篇关于服务寿命瞬态,作用域,单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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