在 IConfigureOptions 中获取 UserManager 实例

Get UserManager instance inside IConfigureOptions

是否可以在 "Configure" (IConfigureOptions) 中获取 UserManager 的自定义实例?当我尝试在 "Configure" 中获取实例时,在 ApplicationUserManager class 中出现以下错误。谢谢!

System.InvalidOperationException: 'ValueFactory attempted to access the Value property of this instance.'

我的代码

ConfigureIdentityOptions

public class ConfigureIdentityOptions : IConfigureOptions<IdentityOptions>
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ConfigureIdentityOptions(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public void Configure(IdentityOptions identityOptions)
    {
        using (var currentScope = _serviceScopeFactory.CreateScope())
        {
            using (var userManager = currentScope.ServiceProvider.GetRequiredService<ApplicationUserManager>())
            {

            }
        }
    }
}

配置服务

public void ConfigureServices(IServiceCollection serviceCollection)
{
    serviceCollection.AddDbContext<DatabaseContext>(x =>
        x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    serviceCollection.ConfigureOptions<ConfigureIdentityOptions>();

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

ApplicationUserManager

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> userStore, IOptions<IdentityOptions> optionsAccessor,
        IPasswordHasher<ApplicationUser> passwordHasher,
        IEnumerable<IUserValidator<ApplicationUser>> userValidators,
        IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber identityErrorDescriber, IServiceProvider serviceProvider,
        ILogger<UserManager<ApplicationUser>> logger) :
        base(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer,
            identityErrorDescriber,
            serviceProvider, logger)
    { }
}

我觉得尝试做你想做的事是不对的。如果你想从正常地方(appsettings.json、环境等)以外的地方读取配置,那么你应该创建一个配置提供程序(参见 here),然后你可以正常访问配置.