微软的依赖注入框架中Autofac的聚合服务相当于什么

Ara*_*ash 6 c# dependency-injection .net-core asp.net-core

有一个 C# asp.net 核心项目,我看到一些构造函数中注入的接口数量不断增长。在某些情况下,预计它可能会超过 30 或 40 个接口。

一些谷歌搜索让我找到了Autofac 的聚合服务。我的问题是,asp.net core 的 DI 框架中是否有等价物来避免将许多接口传递给构造函数?

pok*_*oke 5

正如 Evk 在评论中提到的,at 的依赖注入容器Microsoft.Extensions.DependencyInjection故意是一个非常简单的容器。如果您需要更强大的功能,您应该考虑切换到完整的 DI 容器。ASP.NET Core 的构建是为了允许交换 DI 容器,并且实际上这样做并不困难。Autofac 有一个关于如何操作的指南。

\n\n

话虽这么说,Autofac\xe2\x80\x99s 聚合服务并没有那么神奇。当然,您可以构建像 Autofac 那样的东西,并使用 Castle DynamicProxy 自动实现聚合服务。但您也可以简单地手动创建这样的聚合服务:

\n\n
public class MyAggregateService\n{\n    public IFirstService FirstService { get; }\n    public ISecondService SecondService { get; }\n    public IThirdService ThirdService { get; }\n    public IFourthService FourthService { get; }\n\n    public MyAggregateService (IFirstService first, ISecondService second, IThirdService third, IFourthService fourth)\n    {\n        FirstService = first;\n        SecondService = second;\n        ThirdService = third;\n        FourthService = fourth;\n    }\n}\n\n// then register that in the container\nservices.AddTransient<MyAggregateService>();\n\n// and depend on it in the controller\npublic MyController (MyAggregateService aggregateService)\n{ \xe2\x80\xa6 }\n
Run Code Online (Sandbox Code Playgroud)\n\n

当然,你必须多写一点,但它\xe2\x80\x99实际上并没有多写多少。如果您可以不用 Autofac 提供的那些高级功能,那么这实际上非常简单且快速完成。

\n