新的 ApplicationDbContext() 与 HttpContext.GetOwinContext().Get<ApplicationDbContext>();

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

我对哪种方式更好以及使用哪种方式有点困惑。当然,如果你总能得到 HttpContext.GetOwinContext().Get();那为什么还要创建一个新的 A​​pplicationDbContext 并冒险加倍对象等?

注意:我在这里专门谈论 Web 应用程序。

您创建并可在 MVC 应用程序中使用 HttpContext.GetOwinContext().Get<ApplicationDbContext>(); 检索的 DbContext 实例可以留作身份框架专用。

如果您需要 DbContext 的实例以在您的应用程序中进行一般使用,您可以使用 IoC 容器(依赖项注入)为您提供一个新的实例,作为需要时和请求范围内的实例想要。

您不应该需要检索 DbContext 的身份框架实例以在您的应用程序中使用,它将独立于您的应用程序进行管理,您可以管理自己的生命周期。

因为您在 Owin Startup class 中将它们连接起来以使用您的 DbContext 实例,它们将在后台使用它,并在需要时创建和销毁实例。

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>();

来自https://blogs.msdn.microsoft.com/webdev/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity/