title: Is there any way to configure owin startup.cs to be run before global asax application start?
body: <p>I'm trying to implement the container per request and transaction per request patterns in MVC 5. I've written most of the code for it leveraging the global asax. I am having trouble with multiple contexts being created though because owin is creating new DbContext classes as part of it's startup.cs.  Is there any way I can have owin run before the global asax application start event so that I can retrieve the existing context that was created there?  I'm new to these patterns so if that question doesn't sound right I'm open to alternate suggestions.</p>
  
  <pre><code>public IContainer Container
  {
      get
      {
          return (IContainer)HttpContext.Current.Items["_Container"];
      }
      set
      {
          HttpContext.Current.Items["_Container"] = value;
      }
  }
  
  protected void Application_Start()
  {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
  
      ////Database.SetInitializer(new MigrateDatabaseToLatestVersion&lt;ApplicationDbContext, Configuration&gt;());
  
  
      DependencyResolver.SetResolver(
          new StructureMapDependencyResolver(() =&gt; Container ?? IoC.Container));
  
      IoC.Container.Configure(cfg =&gt;
      {
          cfg.AddRegistry(new StandardRegistry());
          cfg.AddRegistry(new ControllerRegistry());
          cfg.AddRegistry(new ActionFilterRegistry(
              () =&gt; Container ?? IoC.Container));
          cfg.AddRegistry(new MvcRegistry());
          cfg.AddRegistry(new TaskRegistry());
          cfg.AddRegistry(new ModelMetadataRegistry());
      });
  
      using (var container = IoC.Container.GetNestedContainer())
      {
  
          foreach (var task in container.GetAllInstances&lt;IRunAtInit&gt;())
          {
              task.Execute();
          }
  
          foreach (var task in container.GetAllInstances&lt;IRunAtStartup&gt;())
          {
              task.Execute();
          }
      }
  }
  
  public void Application_BeginRequest()
  {
      Container = IoC.Container.GetNestedContainer();
  
      foreach (var task in Container.GetAllInstances&lt;IRunOnEachRequest&gt;())
      {
          task.Execute();
      }
  }
  
  public void Application_Error()
  {
      foreach (var task in Container.GetAllInstances&lt;IRunOnError&gt;())
      {
          task.Execute();
      }
  }
  
  public void Application_EndRequest()
  {
      try
      {
          foreach (var task in
              Container.GetAllInstances&lt;IRunAfterEachRequest&gt;())
          {
              task.Execute();
          }
      }
      finally
      {
          Container.Dispose();
          Container = null;
      }
  }
  </code></pre>
  
  <p>Structure Map Class</p>
  
  <pre><code>public class StructureMapDependencyResolver : IDependencyResolver
  {
      private readonly Func&lt;IContainer&gt; _factory;
  
      public StructureMapDependencyResolver(Func&lt;IContainer&gt; factory)
      {
          _factory = factory;
      }
  
      public object GetService(Type serviceType)
      {
          if (serviceType == null)
          {
              return null;
          }
  
          var factory = _factory();
  
          return serviceType.IsAbstract || serviceType.IsInterface
              ? factory.TryGetInstance(serviceType)
              : factory.GetInstance(serviceType);
      }
  
      public IEnumerable&lt;object&gt; GetServices(Type serviceType)
      {
          return _factory().GetAllInstances(serviceType).Cast&lt;object&gt;();
      }
  </code></pre>
  
  <p>Startup for Owin - this is being executed both after Global ASAX on start and on each request, but after the global ASAX code.  I would like to be able to either set the OWIN context to an existing context instance or have this code execute first and get the context that was created in startup.</p>
  
  <pre><code>    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
      public void ConfigureAuth(IAppBuilder app)
      {
  
          // Configure the db context, user manager and signin manager to use a single instance per request
          app.CreatePerOwinContext(ApplicationDbContext.Create);
          app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
          app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;(ApplicationSignInManager.Create);
  
          // Enable the application to use a cookie to store information for the signed in user
          // and to use a cookie to temporarily store information about a user logging in with a third party login provider
          // Configure the sign in cookie
          app.UseCookieAuthentication(new CookieAuthenticationOptions
          {
              AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
              LoginPath = new PathString("/Account/Login"),
              Provider = new CookieAuthenticationProvider
              {
                  // Enables the application to validate the security stamp when the user logs in.
                  // This is a security feature which is used when you change a password or add an external login to your account.  
                  OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser&gt;(
                      validateInterval: TimeSpan.FromMinutes(30),
                      regenerateIdentity: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager))
              }
          });            
          app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  
          // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
          app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
  
          // Enables the application to remember the second login verification factor such as phone or email.
          // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
          // This is similar to the RememberMe option when you log in.
          app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
  
          // Uncomment the following lines to enable logging in with third party login providers
          //app.UseMicrosoftAccountAuthentication(
          //    clientId: "",
          //    clientSecret: "");
  
          //app.UseTwitterAuthentication(
          //   consumerKey: "",
          //   consumerSecret: "");
  
          //app.UseFacebookAuthentication(
          //   appId: "",
          //   appSecret: "");
  
          //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
          //{
          //    ClientId = "",
          //    ClientSecret = ""
          //});
      }
  }
  </code></pre>