在DI中共享依赖项时,如何避免注入全局状态? [英] How do you avoid injecting global state when sharing dependencies in DI?

查看:90
本文介绍了在DI中共享依赖项时,如何避免注入全局状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您将单个数据库连接注入到少数几个服务类。他们现在共享本质上是全球可变的状态。 DI框架如何处理?他们是否:

Imagine you inject a single database connection to a handful of service classes. They now share what's essentially a global mutable state. How do DI frameworks deal with this? Do they:


  • 在注入之前冻结依赖项?

  • 仅共享不可变对象吗?

  • 在装饰器中包装每个依赖项以仅提供确切的依赖项?

我尝试搜索此内容,但我感到有些惊讶找不到很多。随时提供链接。

I tried searching for this and am a bit surprised I didn't find much. Feel free to provide links.

相关: https:// en .wikipedia.org / wiki / Principle_of_least_privilege

推荐答案

大多数DI容器都提供了在生命周期内注册依赖项的功能。例如,在.net核心DI中,您可以注册具有三个不同生存期的服务:

Most DI containers provide the feature of registering a dependency within a Lifetime. For instance in .net core DI you can register a service with three different lifetimes:


  • Singleton:只有一个实例。该服务的所有使用者将使用该实例。如果一个使用者更改了该依赖关系的状态,则所有其他使用者都将看到该更改。

  • 范围:每个范围有一个实例,其中一个范围是一个Web请求。如果使用者改变了范围服务的状态,则将在同一Web请求中运行的所有其他使用者都将看到更改。

  • 瞬态:每个使用者都使用服务的不同实例。

始终在.net核心中,(默认情况下)将DBContext作为作用域服务添加,这意味着在同一Web请求中,所有使用者将使用相同的实例,当您需要在不同使用者之间(或在不同存储库之间更好地)运行事务时,这将很有用。

Always in .net core, the DBContext is (by default) added as a scoped service, this means that in the same web request all the consumers will use the same instance and this is useful when you need to run a transaction across different consumers (or better across different repositories).

这篇关于在DI中共享依赖项时,如何避免注入全局状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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