在配置服务中注入基于注入的用户选项 IOptions<>注入数据保护



我在这里有点困惑,关于如何根据用户设置以及从services.Configure<UserSettingsConfig>(Configuration.GetSection("UserSettings"));注入的用户设置在ConfigureServices(IServiceCollection services)中注入数据保护。

下面的值appName_from_appsettings_jsondirInfo_from_appsettings_json应该来自注入的UserSettingsConfig,并且可以通过注入IOptions<UserSettingsConfig>访问其他任何地方,但不能在这里。

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.Configure<UserSettingsConfig>(Configuration.GetSection("UserSettings"));
    services.AddMvc();
    services.AddScoped<DevOnlyActionFilter>();
    services.AddDataProtection()
        .SetApplicationName(appName_from_appsettings_json)
        .PersistKeysToFileSystem(dirInfo_from_appsettings_json);
}

我已经找到了实现目标的方法,而无需将 DI 与 var sharedDataProtectionAppName = configuration.GetValue<string>("UserSettings:SharedDataProtection:ApplicationName"); 等代码一起使用

我有一种感觉,我已经在本文中找到了解决方案,http://andrewlock.net/access-services-inside-options-and-startup-using-configureoptions/似乎我不知道如何将其应用于我的情况。我需要一种方法来根据注入IOptions<UserSettingsConfig>的值注入DataProtection.在您看来,最干净的方法是什么?

更新:我找到了一个基于我可以从ConfigureServices调用的代码类型的解决方案,但我仍然想知道这是否是最好的方法。

var userSettingsConfig = services.BuildServiceProvider().GetServices<IOptions<UserSettingsConfig>>().First();

您也可以使用扩展方法.Bind() 。此方法将尝试通过匹配配置中的键将值绑定到 Configuration 对象。

// Add framework services.
var userSettingsConfig = new UserSettingsConfig();
Configuration.GetSection("UserSettings").Bind(userSettingsConfig);
services.Configure<UserSettingsConfig>(Configuration.GetSection("UserSettings"));
services.AddMvc();
services.AddScoped<DevOnlyActionFilter>();
services.AddDataProtection()
    .SetApplicationName(userSettingsConfig.appName)
    .PersistKeysToFileSystem(userSettingsConfig.DirInfo);

最新更新