How do I register a different service implementation within a scope using miscrosoft's default DI mechanism?
My case is this:
I have a service (let's call it MyJobService) that depends on context values (logged in user and some other information). I have registered another service (UserSessionProvider) that reads the data needed from the current HttpContext. But my initial service may also run in a background job, where HttpContext does not exist, but the job is fired from within a web request.
So I would like to have a second implementation of UserSessionProvider where the information of current user is not read from the http context but it would be passed as readonly data to the service implementation and then I would use this instance of UserSessionProvider as the implementation within the created scope.
public IActionResult ControllerMethod( [FromService] IUserSessionProvider sessionProvider, // this instance reads from http context [FromServices] IServiceProvider sp) { var staticSessionProvider = new StaticDataSessionProvider( // this instance uses what you pass to the constructor userName: sessionProvider.userName, userData: sessionProvider.userData ); ExecuteInBackground(()=>{ using(var scope = sp.CreateScope()){ scope.AddScoped<IUserSessionProvider>(staticSessionProvider); // can I do that? var myJob=scope.ServiceProvider.GetService<MyJobService>(); // here 'myJob' would use the staticDataSessionProvider instance myJob.Run(); } }); }