gpt4 book ai didi

c# - ApplicationUserManager.Create 在每个请求上调用

转载 作者:可可西里 更新时间:2023-11-01 08:29:56 26 4
gpt4 key购买 nike

我正在使用 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,
};
...

另外,我觉得跟这个有关系

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

我该怎么做才能让这个“创建”只在需要时被调用。我不想在不需要时实例化密码验证器和其他东西

谢谢

最佳答案

不确定这是否仍然打开,但是...我也不喜欢每次调用 ApplicationUserManager 的方式,所以我决定将其更改为单例。

对象的dispose方法会被自动调用,除非你在传入create的时候也传入一个析构函数回调。

所以我的 ApplicationUserManager 现在看起来像这样:

public class ApplicationUserManager : UserManager<SmartUser, Guid>
{

//This manager seems to get re-created on every call! So rather keep a singleton...
private static ApplicationUserManager _userManager;

private ApplicationUserManager(IUserStore<SmartUser, Guid> store)
: base(store)
{
}

internal static void Destroy(IdentityFactoryOptions<ApplicationUserManager> options, ApplicationUserManager manager)
{
//We don't ever want to destroy our singleton - so just ignore
}

internal static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
if (_userManager == null)
{
lock (typeof(ApplicationUserManager))
{
if (_userManager == null)
_userManager = CreateManager(options, context);
}
}

return _userManager;
}

private static ApplicationUserManager CreateManager(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
... your existing Create code ...
}
}

在 Startup.Auth 中,我传入了 Destroy 回调

        app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create, ApplicationUserManager.Destroy);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

另一种选择是忽略“每个请求调用的注册代码”并使 UserStore 成为单例....

尚未发现这种强硬方法的缺点...

关于c# - ApplicationUserManager.Create 在每个请求上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33764891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com