何时使用以下 Transient、scoped 和 singleton

When to use following Transient, scoped and singleton

我阅读了一些关于此的文章,并且了解了如何使用 Transient、Scoped 和 Singleton,但我对何时使用其中之一感到困惑。

我的理解:

Singleton:在需要存储员工数量的情况下,您可以创建单例,因为每次创建新员工时都会增加数量,因此在这种情况下您需要单例。

Scoped: 例如你在玩游戏,生命数是5,然后你需要在玩家游戏结束时减少生命数。在每一个新的时间你都需要新的实例,因为每一个新的时间你需要的生命数是 5.

Transient:什么时候使用Transient??

如有错误请指正。 并尽可能给出所有这些中更好的例子。

据我所知,Singleton一般用于全局单例。例如,您将有一个图像存储服务,您可以有一个服务从给定位置加载图像并将它们保存在内存中以备将来使用。

范围内的生命周期表示每个客户端请求创建一次服务。通常我们会将其用于 sql 连接。这意味着它将根据请求创建和处理 sql 连接。

每次从服务容器请求它们时,都会创建一个短暂的生命周期服务。例如,在一个请求期间,您使用 httpclient 服务多次调用其他 web api 请求,但 web api 端点不同。届时,您会将 httpclient 服务注册为临时服务。这意味着每次当您调用 httpclient 服务时,它都会创建一个新的 httpclient 来发送不使用相同请求的请求。

请注意,Microsoft 提供了建议 here and here

When designing services for dependency injection:

  • Avoid stateful, static classes and members. Avoid creating global state by designing apps to use singleton services instead.
  • Avoid direct instantiation of dependent classes within services. Direct instantiation couples the code to a particular implementation.
  • Make services small, well-factored, and easily tested.