AddSingleton - 在 运行 应用程序上创建

AddSingleton - Create on run application

我需要在应用程序启动时创建单例。在此示例中,我创建了一个具有新值的 IdentityOptions 实例。问题是当我启动应用程序并且我想创建一个新用户时,它没有采用值 125(它一直使用 6,这是默认值),但是如果我从控制器修改该值(参见示例) ,一切正常。我知道实例是在第一次请求时创建的,但是是否可以在启动应用程序时创建它?因为我的想法是从数据库中加载这些值。

Startup.cs

public void ConfigureServices(IServiceCollection serviceCollection)
{
    ...
    ...
    ...

    serviceCollection.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<DatabaseContext>()
        .AddRoleStore<ApplicationRoleStore>()
        .AddUserStore<ApplicationUserStore>()
        .AddUserManager<ApplicationUserManager>()
        .AddRoleManager<ApplicationRoleManager>()
        .AddSignInManager<ApplicationSignInManager>()
        .AddDefaultTokenProviders();

    ...
    ...
    ...

    serviceCollection.AddSingleton(serviceProvider =>
    {
        //using (var currentContext = serviceProvider.CreateScope().ServiceProvider.GetRequiredService<MyIdentityDatabaseContext>())
        {
            return new IdentityOptions
            {
                Password = new PasswordOptions
                {
                    RequiredLength = 125
                }
            };
        }
    });
}

例子

public class TestController : BaseController<TestController>
{
    private readonly IOptions<IdentityOptions> _myOptions;

    public TestController(IOptions<IdentityOptions> myOptions)
    {
        _myOptions = myOptions;
    }

    [HttpGet]
    [Route("TestConfigureOptions")]
    public IActionResult TestConfigureOptions()
    {
        // 1 - Before assigning 124, the value it has is 6. WHY?

        _myOptions.Password.RequiredLength = 124;

        // 2 - After assigning the 124 and trying to create a user with an incorrect password length, I am informed that the minimum is 124, that this is correct.

        return Ok();
    }

}

因为那是两个单独的注册。

AddIdentity 会使用 services.Configure<IdentityOptions>(...)

通过选项添加 IdentityOptions

这将允许 IOptions<IdentityOptions> 按预期注入。

第二次报名

serviceCollection.AddSingleton(serviceProvider => { 

        return new IdentityOptions {
            Password = new PasswordOptions {
                RequiredLength = 125
            }
        };

});

与选项无关

如果您想更改默认设置,请更新配置。

serviceCollection.Configure<IdentityOptions>(options => {
    options.Password.RequiredLength = 125;
});

调用AddIdentity一次性完成时也有重载

serviceCollection.AddIdentity<ApplicationUser, ApplicationRole>(options => {
    options.Password.RequiredLength = 125;
})