Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New ApplicationDbContext() vs HttpContext.GetOwinContext().Get<ApplicationDbContext>();

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.

like image 219
Fabis Avatar asked May 11 '15 08:05

Fabis


2 Answers

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.

like image 94
Luke Avatar answered Nov 15 '22 16:11

Luke


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/

like image 24
Toolkit Avatar answered Nov 15 '22 17:11

Toolkit