代码之家  ›  专栏  ›  技术社区  ›  Wing Kui Tsoi

ASP.NET MVC应用程序上下文创建

  •  1
  • Wing Kui Tsoi  · 技术社区  · 7 年前

    有人能解释一下创建方法的用途吗?

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
      public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
      {
      }
    
      public static ApplicationDbContext Create()
      {
        return new ApplicationDbContext();
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   TanvirArjel    7 年前

    如果你看到这个的参考文献 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.