I'm a little confused about which way is better and which one to use. Surely if you can always get HttpContext.GetOwinContext().Get(); then why even create a new ApplicationDbContext and risk doubling objects etc.?
Note: I'm specifically talking about a Web application here.
The DbContext instance that you create and can be retrieved using HttpContext.GetOwinContext().Get<ApplicationDbContext>();
within your MVC application can be left exclusively for the use of Identity Framework.
If you need an instance of your DbContext for general use within your application, you can make use of an IoC Container (dependency injection) to provide you with a fresh instance of it as an when required and in request scope if desired.
You shouldn't need to retrieve the identity framework instance of the DbContext for the use within your application, it will be managed independently of your application and you can manage your own lifecycle.
Because you wired these up within the Owin Startup class to use an instance of your DbContext, they will make use of it under the hood and will create and destroy instances as and when it is required.
The solution is to store a single instance of UserManager and DbContext per request and reuse them throughout the application. Since Identity hooks into the OWIN pipeline via cookie middleware, 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 with the DbContext object directly we can get the instance of the class from the OWIN context as mentioned earlier using the ‘Get’ method
var dbContext = context.Get<ApplicationDbContext>();
From https://blogs.msdn.microsoft.com/webdev/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With