Search code examples
.net.net-coredependency-injection.net-5service-provider

Is it possible to include an argument in the IServiceScopeFactory.ServiceProvider.GetRequiredService<IServiceClass>()?


Say I have the following code in the "HostedService" class using a IServiceScopeFactory to run a scope and create the service class instance (as explained here -> How should I inject a DbContext instance into an IHostedService?):

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

So, I'd like to do something akin as in the below code to include a parameter inside the instance service creation:

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

but this done using the IServiceScopeFactory class. If not, is it possible to override at all the once DI built in the Startup class at a later stage of the .net core program execution?


Solution

  • IServiceScopeFactory does not allow passing overrides/additional dependencies when creating nested scopes. You need either use 3rd party container which allows adding registrations to a lifetime scope like Autofac (also see this) or redesign your IUserCarrierService so it allows some kind of impersonation mechanism.