每次请求都调用ApplicationUserManager.Create

MDu*_*MDu 14 c# asp.net asp.net-mvc asp.net-identity-2

我正在使用asp.net mvc 5与外部提供商owin提供(facebook,twitter)

每次请求都会调用ApplicationUserManager.Create.登录用户有很多不必要的东西(密码验证器配置或短信和电子邮件服务配置....)

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = true,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 7,
                RequireNonLetterOrDigit = false,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
...
Run Code Online (Sandbox Code Playgroud)

此外,我认为这与此有关

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);
...
Run Code Online (Sandbox Code Playgroud)

如果只在需要时调用此"创建",我该怎么办?我不想在不需要时在那里实例化密码验证器和其他东西

谢谢

Ina*_*ari 0

就个人而言,在这种情况下绝对不建议使用 CreatePerOwinContext。您应该只初始化 DbContext、UserManager 和 SignInManager 一次,并让 EF 和 MVC 确定何时需要新的上下文。MVC 5 和更新版本更有效地使用依赖注入 (DI),从而无需为每个上下文提供单独的实例。

只有当您的代码被视为关键并且需要新的上下文时,您才应该在特定的代码部分而不是站点范围内执行此操作。