【问题标题】:Is it possible to include an argument in the IServiceScopeFactory.ServiceProvider.GetRequiredService<IServiceClass>()?是否可以在 IServiceScopeFactory.ServiceProvider.GetRequiredService<IServiceClass>() 中包含参数?
【发布时间】:2022-01-02 04:03:09
【问题描述】:

假设我在“HostedService”类中有以下代码,使用 IServiceScopeFactory 运行范围并创建服务类实例(如此处所述 -> How should I inject a DbContext instance into an IHostedService?):

using (var scope = ScopeFactory.CreateScope())
{                                 
   var provisioningService = scope.ServiceProvider.GetRequiredService<IProvisioningService>();
}

所以,我想做一些类似于以下代码的操作,以便在实例服务创建中包含一个参数:

services.AddSingleton<IUserCarrierService>(x => new UserCarrierService(user));

但这是使用 IServiceScopeFactory 类完成的。如果没有,是否有可能在 .net 核心程序执行的后期完全覆盖 Startup 类中内置的一次 DI?

【问题讨论】:

    标签: .net .net-core dependency-injection .net-5 service-provider


    【解决方案1】:

    IServiceScopeFactory 在创建嵌套范围时不允许传递覆盖/附加依赖项。您需要使用3rd party container,它允许将注册添加到Autofac(另见this)或重新设计您的IUserCarrierService,以便它允许某种模拟机制。

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多