There will be a time that you want to use services within the ConfigureServices Method. This is strange because, the ConfigureServices actually registers the services. There are multiple ways of achieving this:
Intermediate Service Provider
public void ConfigureService(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<SomeService>();
var sp = services.BuildServiceProvider();
var fooService = sp.GetService<IFooService>();
}
You might ask yourself, will it not end up with multiple service providers? The answer is…YES! Thats why it’s called the intermediate service provider, If you’re resolving a service inside authentication, this is not the way to do it. Imagine a new service provider instance for each time it passes through the authentication middleware…ouch!
Access the service container via the HttpContext.RequestServices
Let’s say you want to use your service somewhere in the authentication middleware, there’s a simple way to do this:
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
// Add framework services.
services.AddOpenIdConnect(options => {
// options.ClientId = ...
options.Events = new OpenIdConnectEvents {
OnTicketReceived = async context => {
var user = (ClaimsIdentity)context.Principal.Identity;
if (user.IsAuthenticated) {
// ...
// get the IFooService service
var fooService = context.HttpContext.RequestServices.GetService<IFooService>();
// ...
}
return;
}
};
});
}
Enjoy!