ASP.NETCore依赖注入单个聚合类而不是多个单独的构造函数注入
c#
在我的 ASP.NET Core Web API 中,我有几个控制器在它们的构造函数中接受超过 4-5 个参数,这对我来说不太好。我正在考虑创建一个聚合类,其中包含我经常使用的所有单独对象。我的意思是,例如,而不是这个:
public SomeController : Controller
{
public SomeController(
IService1 service1,
IService2 service2,
Config1 config1,
Config2 config2)
{
}
}
写这样的东西:
// of course registered in DI services.AddSingleton<MyToolkit>()
public class MyToolkit
{
public MyToolkit(
IService1 service1,
IService2 service2,
Config1 config1,
Config2 config2)
{
...
}
public IService1 Service1 { get; }
public IService2 Service2 { get; }
public Config1 Config1 { get; }
public Config2 Config2 { get; }
}
public SomeController : Controller
{
private readonly MyToolkit _toolkit;
public SomeController(MyToolkit toolkit) { _toolkit = toolkit; }
[HttpGet]
public IActionResult GetSomething()
{
return _toolkit.Service1.GetSomething();
}
}
这种方法(MyToolkit 类)是否违反了任何现代设计原则?这种方法是否被认为是反模式?
回答
首先检查控制器级别是否真的需要所有这些依赖项。
具有许多依赖项通常表明主题类很可能做了太多事情(违反 SRP)。
如果注入到聚合中的那些依赖项只是作为属性公开,那么控制器和聚合对于它执行其功能所需的明确内容是不诚实的。(显式依赖原则)
如果在使用这些依赖项的控制器中发生了功能,并且实际上应该在它自己的类中,则将该功能及其依赖项抽象出来。(关注点分离 - SoC)
您当前基于提供的示例的方法只是在路上踢罐子,可以看作是代码异味。
- @TiberSeptim 这些听起来很像 [交叉问题](https://en.wikipedia.org/wiki/Cross-cutting_concern)
- 如果您正在使用 MediatR,您确定不能在装饰器或使用 MediatR 的 [行为](https://github.com/jbogard/MediatR/wiki/Behaviors) 中应用所有这些“问题”吗?