Can I use static DB context in OwinContext all the time? RRS feed

  • Question

  • User1005437588 posted

    Can I call in 

    var db = SomeClass.GetMyContext();

    Where GetMyContext returns HttpContext.Current.Request.GetOwinContext().Get<MyDbContext>();

    Is is correct thing to do? I am doing it to get access to UserManager inside OwinContext

    Or should I initialize and dispose a new DbContext all the time? 

    Saturday, January 23, 2016 2:42 PM


  • User-2057865890 posted

    Hi Alex71938,

    If you want to register the UserManager and DBContext class with the OWIN context during app start, you could add methods to do that in the ConfigureAuth method. The ‘CreatePerOwinContext<T>’ method is defined in the Microsoft.AspNet.Identity.Owin namespace. This method registers a static callback method which returns an instance of type <T>. 

     To create a static callback method that returns an instance of DbContext 

    public static ApplicationDbContext Create()
        return new ApplicationDbContext();

    Similarly define a method in the ApplicationUserManager that returns an instance of the ApplicationUserManager

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
         var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
         return manager;

    Register these two callback methods in the ConfigureAuth method through the ‘CreatePerOwinContext’ method

    public void ConfigureAuth(IAppBuilder app)

    Per request lifetime management for UserManager class in ASP.NET Identity

    Best Regards,

    Chris Zhao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 25, 2016 1:42 PM