10

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?

DavidG
  • 113,891
  • 12
  • 217
  • 223
Starnuto di topo
  • 3,215
  • 5
  • 32
  • 66
  • 3
    [This answer](https://stackoverflow.com/a/57727839/5402620) shows how to use `IPostConfigureOptions` to support dependency injection in scenarios like this without building the service provider. – Jonathon Chase Nov 11 '19 at 15:36
  • Thanks, @jonathon-chase! that's exactly what I was looking for! – Starnuto di topo Nov 11 '19 at 16:01

0 Answers0