Search code examples
inversion-of-controlcastle-windsorowinasp.net-web-api2asp.net-identity-2

OWIN, IoC, Bootstraping Providers and Preserving Lifestyles


I can't wrap my head around wiring up Providers (OAuth and RefreshToken) defined in an IoC container (Windsor) via OWINs bootstraping (Startup class) and have the Providers lifestyles (PerWebRequest) respected. I'm only having an issue with the Providers, Controllers which have a Scoped lifestyle are working perfectly.

I know this could never work....but based on the following:

public void ConfigureOAuth(IAppBuilder app, WindsorContainer container)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = container.Resolve<IOAuthAuthorizationServerProvider>(),
            RefreshTokenProvider = container.Resolve<IAuthenticationTokenProvider>()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }

Provider and RefreshTokenProvider will be set only once during Startup. I'd need them to be PerWebRequest because the underlying implementations uses a UserManager,UserStore and DBContext which is getting out of synch with DB changes because it's never getting disposed.

Not sure if the answer is in an OwinMiddleware or CreatePerOwinContext() ... I've gone in circles trying to get IoC to work correctly with Providers. Any help would be greatly appreciated.


Solution

  • This pretty much fixed it for me:

    Dependency Injection (using SimpleInjector) and OAuthAuthorizationServerProvider

    The factory method route seemed like the best way to go because of how early it is in OWIN's pipeline.