levis84
levis84

Reputation: 1054

Get a service from the builder.Services.AddAuthentication() method

I want to get a registered service from within the AddAuthentication() method but I cannot do so without re-registering all the services again (in BuildServiceProvider).

I get the warning: "Calling buildserviceprovider from application code results in an additional copy of services."

Is there a way to pass in IServiceCollection? It seems odd it is not already available seeing as I have access to "builder.Services".

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
{
    var context = builder.Services.BuildServiceProvider().GetService<IHttpContextAccessor>();

    //I want to do this but it's not available.:
    options.GetService<IHttpContextAccessor>();
    //OR
    builder.Services.GetService<IHttpContextAccessor>();
}

Upvotes: 1

Views: 1140

Answers (1)

DespeiL
DespeiL

Reputation: 1033

First implement IConfigureNamedOptions

 public class ConfigurationsJwtBearerOptions : IConfigureNamedOptions<ConfigurationsJwtBearerOptions>
    {
        IHttpContextAccessor _httpContext;
        public ConfigurationsJwtBearerOptions(IHttpContextAccessor httpContext)
        {
            _httpContext = httpContext;
        }
        public void Configure(string name, ConfigurationsJwtBearerOptions options)
        {
            Configure(options);
        }
    
        public void Configure(ConfigurationsJwtBearerOptions options)
        {
            //same code that you usually used in  AddJwtBearer (options=>{})
        }
    }

Then in Progam.cs or StarUp.cs

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.ConfigureOptions<ConfigurationsJwtBearerOptions>().AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer();//no need to configurate JwtBearer  options  here ConfigurationsJwtBearerOptions will handle it 

Upvotes: 1

Related Questions