我想在 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/