【发布时间】:2021-11-04 18:38:51
【问题描述】:
上下文:
- 使用 .NET 依赖注入 (.NET Core 3.1)
- WebHostBuilder,使用 Startup.cs 进行配置
- 使用 ConfigureServices(IServiceCollection services) 配置主要服务
在这个方法中,我需要像这样调用单例服务的方法...
services.AddSingleton((sp) =>
{
var svc = sp.GetRequiredService<Dependency_A>();
var setConfig = new ConfigurationDataClass(svc);
setConfig = setConfig.CallMethod().Result;
return setConfig;
});
//-- Need to get value stored in setConfig here somehow without using
//-- services.BuildServiceProvider()
//-- Because it creates a whole other container which I want to avoid doing
//-- After getting setConfig.OtherData
//-- I'll use to pass other data to subsequent services that need it
不幸的是,由于现有设计结构的限制,我无法更改后面的服务从配置数据服务接收数据的方式,我仅限于找到一个可以让我避免的阻塞调用创建一个重复的容器。感谢任何建议,因为我想用尽所有可能性。
【问题讨论】:
-
这可能是XY problem。
-
当然不是。这是一个我无法改变的约束问题。要么我在 Microsoft 文档中没有找到适合此流程的某种方式,要么不幸的是 .BuildServiceProvider()。
标签: c# dependency-injection dependencies asp.net-core-webapi