Reputation: 14917
I'm using Auth0's SDK for authentication and in their sample code, they created an event listener such as OnRedirectToIdentityProviderForSignOut()
in ConfigureServices()
.
I need to do something similar and add some of my own code that does some logging and reads/writes to the database when an event like this is fired.
How do I resolve services in event handlers like OnRedirectToIdentityProviderForSignOut()?
A comment like this one suggests that I don't resolve instances in ConfigureServices()
because a) the ServiceProvider
will be different than the one that ASP.NET Core will use when handling requests b) the lifetime of all instances is indefinite (based on my understanding)
How can I resolve instances in my Auth0 event handlers (eg: OnRedirectToIdentityProviderForSignOut())
where it will be the same one that ASP.NET Core uses when handling HTTP requests so that scoped services will be destroyed at the end of the HTTP request?
I'm concerned about memory leaks.
some sample code to help clarify what I mean (check comments)
public class Startup {
//...
public virtual void ConfigureServices(IServiceCollection services) {
//...
services.AddOpenIdConnect("Auth0", options => {
options.Events = new OpenIdConnectEvents
{
OnTicketReceived = async e =>
{
//How do I get instances of my services (eg: ILogger<Startup>) at this point? I want to avoid calling services.BuildServiceProvider()
//because it won't be the same service provider that ASP.NET Core will use to service HTTP request and thus will cause memory leaks
},
});
}
}
Upvotes: 3
Views: 923
Reputation: 247591
After checking a hunch, the event delegate's event args is TicketReceivedContext Class
which can give you access to the service provider within the HttpContext
.
//...
services.AddOpenIdConnect("Auth0", options => {
options.Events = new OpenIdConnectEvents {
OnTicketReceived = async e => {
//How do I get instances of my services (eg: ILogger<Startup>) at this point?
IServiceProvider serviceProvider = e.HttpContext.RequestServices;
var logger = serviceProvider.GetService<ILogger<Startup>>();
//...
},
};
});
//...
A similar format can also be followed for the other events / handlers
Upvotes: 7