I have an ASP.NET Core 3.0 application. In the Startup class, in method
public void ConfigureServices(IServiceCollection services)
I would like to configure authentication so that JWT is handled by my implementation of ISecurityTokenValidator: CustomJwtSecurityTokenHandler. To do that I need to get an instance of my implementation class, CustomJwtSecurityTokenHandler, whose constructor needs some services to be injected. for this reason, I need to call:
var serviceProvider = services.BuildServiceProvider();
in order to create a "temporary" serviceProvider to get my instance of CustomJwtSecurityTokenHandler with injected parameters.
I ended up with this code (that works fine!):
services.AddAuthentication(authenticationOptions =>
{
authenticationOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
authenticationOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwtBearerOptions =>
{
jwtBearerOptions.SecurityTokenValidators.Clear();
CustomJwtSecurityTokenHandler customJwtSecurityTokenHandler;
{
// create a temporary serviceProvider, in order to retrieve a CustomJwtSecurityTokenHandler (supposed to be registered as addin!).
var serviceProvider = services.BuildServiceProvider();
customJwtSecurityTokenHandler = serviceProvider.GetService<CustomJwtSecurityTokenHandler>();
}
//below line adds the custom validator class
jwtBearerOptions.SecurityTokenValidators.Add(customJwtSecurityTokenHandler);
});
Only, calling services.BuildServiceProvider() from within method ConfigureServices has some issues (with singletons, for example) and I get the following warning:
ASP0000 Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.
So.. What is the good way to configure a service that requires some other registered services to be injected?