ASP.NET MVC ApplicationDbContext创建

时间:2019-01-23 05:06:37

标签: c# database asp.net-identity

有人可以解释创建方法的用途吗?

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
  public ApplicationDbContext()
    : base("DefaultConnection", throwIfV1Schema: false)
  {
  }

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

1 个答案:

答案 0 :(得分:2)

如果您看到此Create静态方法的引用,则会发现此方法已在ConfigureAuth文件中Startup子类的Startup.Auth.cs方法中使用App_start文件夹如下:

public partial class Startup
{

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);

        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Removed other codes for brevity
    }
}

此处CreatePerOwinContext注册一个静态回调,您的应用程序将使用该回调来获取指定类型的新实例。 每个请求将调用一次该回调,并将该对象存储在OwinContext中,以便您可以在整个应用程序中使用它们。

Here is more details with example.