I'm developing a NuGet package to handle the authentication configuration for many ASP.NET Core applications in my company.
For it to work, it needs some configuration that is only available in the context of a http request (it has to do with multi-tenancy), not during the application startup. To handle that, the registration of the package in my Program.cs file accepts a function that takes as a parameter a fully configured IServiceProvider and returns the required configuration, as shown here:
public static AuthenticationBuilder AddFederatedAuthentication(
this IServiceCollection services,
Func<IServiceProvider, FederatedAuthenticationConfiguration> configurationProvider)
{
services.AddSingleton<Func<FederatedAuthenticationConfiguration>>(
serviceProvider => () => configurationProvider(serviceProvider));
// Rest of the registration...
return authenticationBuilder;
}
Each application using the package must provide that function with an implementation specific to the application.
The problem that I'm facing is that in one application, the function requires a service that is registered as scoped in the DI engine (var myService= serviceProvider.GetRequiredService<IMyScopedService>();), and that causes the following exception to be thrown:
InvalidOperationException: Cannot resolve scoped service 'MyNamespace.IMyScopedService' from root provider
However, I can't change the registration of that service to be a singleton.
Is there any way to use a "non-root" provider to get that scoped service? More generally, is there a way to allow injecting "HTTP request specific" configuration in my authentication configuration?