我有一个具有多个构造函数依赖关系的类。它可能值得重构,但后来。
我知道Autofac可以通过以下代码来实现:
builder.RegisterType<ConfigReader>()
.As<IConfigReader>()
.WithParameter("configSectionName", "sectionName");
这意味着&#34;在解析参数sectionName
时使用configSectionName
并使用默认流量来完成剩下的&#34; 。
问题是,在DI内置的.Net核心中,除了工厂方法迫使我在每个其他参数上手动调用serviceProvider.GetService<IFoo>()
之外,找不到任何方法。这非常烦人。
可以直接表达,还是我必须选择autofac / workarounds?我目前讨厌的代码是:
serviceCollection.AddTransient<IPollService, PollService>(provider => new PollService(
provider.GetService<IEthereumSettings>(),
provider.GetService<EthereumClientProvider>(),
provider.GetService<ABIDeserialiser>(),
provider.GetService<ConstructorCallEncoder>(),
provider.GetService<IJsonSerializer>(),
provider.GetService<ILogger>(),
rootContractAddress));
我可以添加一些像RootContractConfig
这样的类型并注册它,但是我必须修改我的API以使DI快乐,这似乎很难看。
答案 0 :(得分:4)
按照设计,ASP.NET Core中的内置DI仅支持入门所需的一小部分功能。对于更高级的方案,可以使用不同的DI容器替换内置DI容器。
因此,如果您想使用Autofac,可以将内置DI替换为described in the ASP.NET Core docs或Autofac's documentation for ASP.NET Core integration。