c# - 依赖注入(inject): setting and sharing properties of scoped service in ASP. NET Core

标签 c# asp.net-core dependency-injection locking inversion-of-control

我想在 Controller 中的某些注入(inject)服务中设置属性,以便稍后在同一请求期间将该服务注入(inject)到其他位置时滥用它,所以我希望只要服务作为作用域注入(inject),该属性就不会改变。

这种方法安全吗?或者您建议如何实现这种行为?

MyController(IServiceWithProperty serviceWithProperty) {
  _serviceWithProperty = serviceWithProperty;
}

public IActionResult Get(int settingToSet) {
  _serviceWithProperty.SetProperty(settingToSet);
  return Ok(_anotherService.GetSomething()); 
}

正如我所说,AnotherService 也注入(inject) ServiceWithProperty

public class AnotherService : IAnotherService {
  public AnotherService(IServiceWithProperty serviceWithProperty) {
    _serviceWithProperty = serviceWithProperty;
  }

  public string GetSomething() {
    int prop = _serviceWithProperty.GetProperty(); //here I expect to get property which has been set in controller, would that work and is it fine to do it like that?
  } 
}

最佳答案

一旦代码库规模增大,这两个服务之间的交互将很难遵循。即使给出了这个简单的示例(顺便说一句,很好地将问题简化为本质),我也必须查看代码几分钟才能了解发生了什么。

此外,这样的设计似乎接近违反Liskov Substitution Principle (LSP),因为它只有在使用特定的、具体的实现时才会起作用。根据 LSP,您应该能够在不改变系统正确性的情况下将一种子类型与另一种子类型交换。这里可能吗?您能否将您想要的 IServiceWithProperty 实现替换为另一个不执行任何操作的实现?

相反,请遵循 Dependency Inversion Principle ,由此得出客户应该定义抽象。因此,如果 MyController 需要一个可以将 int 转换为其他内容的抽象,那么这就是它需要的抽象:

MyController(ITranslator translator) {
  _translator = translator;
}

public IActionResult Get(int setting) {
  return Ok(_translator.Translate(setting)); 
}

下一步是弄清楚如何实现 ITranslator 接口(interface)。

关于c# - 依赖注入(inject): setting and sharing properties of scoped service in ASP. NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52993207/

相关文章:

asp.net-core - TagHelper 用于将路由值作为链接的一部分传递

ios - 类中的 Swift 4 Viewcontroller 依赖注入(inject)

c# - Visual Studio 断点警告

c# - 代码运行时进度条(跑马灯)消失

c# - 具有相关事件 ID 的 EventSource 跟踪

asp.net-core - 如何使用 Asp.Net Core 2.2/IdentityServer4/SP.NET Core Identity 手动散列密码

c# - 仅授权 ASP.NET Core 中的某些 Http 方法

C#,带变量和不带变量的属性之间的区别

c# - 具有依赖注入(inject)的 AutoMapper 不映射配置文件?

database - 是否有教程或书籍将 MVVM + DI 和使用数据库中的数据合二为一?