New ApplicationDbContext () vs HttpContext.GetOwinContext (). Get <ApplicationDbContext> ();
The DbContext instance that you create and which can be obtained using HttpContext.GetOwinContext().Get<ApplicationDbContext>(); in your MVC application, should be exclusively for using the Identity Framework methods / classes.
You do not need to retrieve this instance of DbContext for use in your application, especially since it will be managed independently of your application. You should simply use instances of the Identity Framework classes using this method, such as authentication manager, role manager, and user manager β examples below:
// Get the identity framework authentication manager var authManager = Request.GetOwinContext().Authentication; // Get the identity framework role manager var roleManager = Request.GetOwinContext().Get<ApplicationRoleManager>(); // Get the identity framework user manager var userManager = Request.GetOwinContext().Get<ApplicationUserManager>(); Since you connected them to the Owin Startup class to use an instance of your DbContext, they will use it under the hood and will create and destroy instances as necessary.
If you need an instance of your DbContext for general use in your application, you should use an IoC container (dependency injection) to provide you with a fresh copy of it if necessary.
The solution is to store one instance of UserManager and DbContext for each request and reuse them throughout the application. Because Identity connects to the OWIN pipeline through the middleware cookie, we can store the UserManager and DbContext in the OWIN context object and retrieve them as needed
Also in the application, if we need to work directly with the DbContext object, we can get an instance of the class from the OWIN context, as mentioned earlier, using the Get method
var dbContext = context.Get<ApplicationDbContext>();