ASP.NET Core Dependency Injection inside Startup.Configure -
i using cookie middleware authenticate user. have been following this official tutorial.
inside startup
class, excerpt configure
method looks this:
public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory) { // ... // cookie-based authentication app.usecookieauthentication(new cookieauthenticationoptions() { authenticationscheme = cookieauthenticationdefaults.authenticationscheme, automaticauthenticate = true, automaticchallenge = true, events = new customcookieauthenticationevents(app), }); // ... }
the customcookieauthenticationevents
class defined follows:
public class customcookieauthenticationevents : cookieauthenticationevents { private iapplicationbuilder _app; private imyservice _myservice = null; private imyservice myservice { { if(_myservice != null) { return _myservice; } else { return _myservice = (imyservice) _app.applicationservices.getservice(typeof(imyservice)); } } } public customcookieauthenticationevents(iapplicationbuilder app) { _app = app; } public override async task validateprincipal(cookievalidateprincipalcontext context) { string sessiontoken = context.principal.claims.firstordefault(x => x.type == claimtypes.sid)?.value; logonsession response = null; var response = await myservice.checksession(sessiontoken); if (response == null) { context.rejectprincipal(); await context.httpcontext.authentication.signoutasync(cookieauthenticationdefaults.authenticationscheme); } } }
since dependency injection not available @ startup.configure
(the services not registered @ point), made bit of workaround:
- pass iapplicationbuilder service
customcookieauthenticationevents
class - fetch
imyservice
upon first request inside read-only property (singleton pattern)
tl;dr
my solution works, it's ugly. there no dependency injection involved, not possible @ time.
the essence of problem must instantiate customcookieauthenticationevents
. far have read source code, there no way around this, because usecookieauthentication
throws exception if omit options
parameter.
any suggestion how can 1 make current solution nicer?
startup.configureservices() called before startup.configure() (see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup more information). dependency injection available @ time ;)
consequence, can resolve dependence in configure method this:
app.applicationservices.getrequiredservice<customcookieauthenticationevents>()
Comments
Post a Comment