You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在依赖注入中结合关联服务使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:42:06