aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Question: Custom Service Provider Not Used Everywhere

Open rjperes opened this issue 1 year ago • 5 comments

So, I register my own IServiceProviderFactory<IServiceCollection> using WebApplicationBuilder.Host.UseServiceProviderFactory<IServiceCollection>, from which I return a custom IServiceProvider implementation. I see that it is called, and appears to work, however, when I try to inject some service into my controller, I see that it does not come from my IServiceProvider, but instead from an ServiceProviderEngineScope. Why is this? Shouldn't the registered factory be used for creating the global IServiceProvider?

rjperes avatar Oct 13 '24 21:10 rjperes

It's because each HTTP request creates a new scope using the root service provider, and then uses the service provider associated with that scope:

https://github.com/dotnet/aspnetcore/blob/049814ca468cad1ea1e29412e0aa3eea182a63c1/src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs#L764-L765

martincostello avatar Oct 13 '24 21:10 martincostello

But from where is IServiceScopeFactory obtained? If I registered my own IServiceProvider, I would expect it to come from there, but it isn't.

rjperes avatar Oct 13 '24 22:10 rjperes

As far as I can tell, it's implemented as part of the built-in service provider via ServiceProviderEngineScope. If your service provider implementation isn't being asked for the IServiceScopeFactory, then I don't know why.

martincostello avatar Oct 14 '24 08:10 martincostello

@martincostello, yes, that's what I'm saying: my custom service provider is not being asked for IServiceScopeFactory, so there must be another place where it is being constructed (another IServiceProvider, I mean).

rjperes avatar Oct 14 '24 09:10 rjperes

This other service provider is used, for example, for the RequestServices property of the HttpContext.

rjperes avatar Oct 17 '24 19:10 rjperes