Search code examples
c#inversion-of-controlautofacowinstartup

Resolve Autofac service within InstancePerLifetimeScope on Owin Startup


I cannot figure out a correct way to resolve a service via Autofac that is used while constructing the Owin context and also disposed at the request end.

Since the OwinContext is still under construction at this point, the LifetimeScope cannot be found by calling HttpContext.Current.GetOwinContext().GetAutofacLifetimeScope(). The OwinContext is not available here yet.

In my code the IAdfsAuthorizationProvider service is resolved directly at the Container, but isn't disposed after a request and lives much longer.

I could create a new LifeTimeScope by calling container.BeginLifetimeScope(), but now the LifeTime is separated of the request and will possibly resolve different instances in the same request. And there is no way to dispose the lifeTimeScope myself at the correct time.

    public void Configure(IAppBuilder app)
    {
         var builder = new ContainerBuilder();    
         builder.RegisterType<AdfsAuthorizationProvider>().As<IAdfsAuthorizationProvider>().InstancePerLifetimeScope();

         var container = builder.Build();

         app.UseAutofacMiddleware(container);

         // **Service that's not binding to the request lifetime.**
         var service = container.Resolve<IAdfsAuthorizationProvider>();

         app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
             {
                Provider = new AuthorizationServerProvider(service),
             });         
          }

Does anyone has a suggestion?


Solution

  • The OAuthAuthorizationServerProvider is a singleton that call methods for all requests.

    This class has not been designed to be injected. If you want to resolve a dependency for one request you will have to resolve it manually using the owinContext provided with each method

    public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override Task GrantAuthorizationCode(
            OAuthGrantAuthorizationCodeContext context)
        {
            IAdfsAuthorizationProvider authorizationProvider =
                context.OwinContext
                       .GetAutofacLifetimeScope()
                       .Resolve<IAdfsAuthorizationProvider>();
    
            return base.GrantAuthorizationCode(context);
        }
    }