The code sample below is from Asp.Net Core ConfigureServices method in Startup.cs.
I am first registering a singleton service called AppState. Subsequent to that, I am configuring OpenIdConnect, and inside the OnTokenValidated lambda, I need to access the AppState service that I just registered in the DI container up above.
What is the most elegant way of accessing the AppState service instance?
I would prefer to not call services.BuildServiceProvider() inside the ConfigureServices method if at all possible.
services.AddSingleton<AppState>();
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
//How to get access to instance of AppState,
//which was added to DI container up above
AppState appState = //{get from DI somehow};
appState.DoSomething();
}
};
});
EDIT: Using the answer below, I edited the code like so, but I can confirm that the OnTokenValidated event is not firing, as opposed to the code above in my original question, which does fire:
services.AddOptions<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme)
.Configure<IServiceScopeFactory>((options, sp) => {
using (var scope = sp.CreateScope())
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
var appState = scope.ServiceProvider.GetRequiredService<AppState>();
await appState.Dosomething();
}
};
}
});
Use the TokenValidatedContext to get access to the current request service provider and resolve the service
services
.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options => {
options.Events = new OpenIdConnectEvents {
OnTokenValidated = async ctx => {
//Get access to instance of AppState,
//which was added to DI container up above
AppState appState = ctx.HttpContext.RequestServices
.GetRequiredService<AppState>();
await appState.DoSomething();
//...
}
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With