在依赖注入中结合关联服务使用implementationFactory的正确方式
关于DI容器中使用implementationFactory处理IDisposable服务的疑问
我查阅了Dependency Injection相关文档,但未找到当委托需要从DI容器解析关联服务以配置另一服务时,使用implementationFactory的正确方法(所有服务均实现IDisposable)。
代码示例
IHost hostBuilder = Host.CreateDefaultBuilder() .ConfigureServices( (context, services) => { services.AddTransient<IExampleTransientService, ExampleTransientService>(); services.AddScoped<IExampleScopedService, ExampleScopedService>(); services.AddSingleton<IExampleSingletonService, ExampleSingletonService>(); }) .ConfigureServices( (context, services) => { services.AddTransient<IServiceLifetimeReporter, ServiceLifetimeReporter>( sp => { var transient = sp.GetRequiredService<IExampleTransientService>(); var scoped = sp.GetRequiredService<IExampleScopedService>(); var singleton = sp.GetRequiredService<IExampleSingletonService>(); return new ServiceLifetimeReporter(transient, scoped, singleton); }); }) .Build();
(我知道上述示例无需implementationFactory也能运行)
疑问点
- DI会为implementationFactory创建本地作用域吗?
- 是否需要在implementationFactory中手动创建本地作用域(使用CreateScope)?
- DI是否会在构建前负责释放(调用Dispose())对象?
- 此类场景及类似场景的正确实现方式是什么?
已尝试的实现方式
- 使用上述示例(未触发Dispose())
- 创建本地作用域(Transient和Scoped生命周期的对象触发了Dispose())
- 使用using调用Dispose()方法(所有生命周期的对象均触发了Dispose())
内容的提问来源于stack exchange,提问作者DmytroHoliaka
相关产品推荐
相关产品推荐

