C# 基于ConfigureServices中的注入用户选项IOptions注入数据保护

C# 基于ConfigureServices中的注入用户选项IOptions注入数据保护,c#,dependency-injection,asp.net-core,C#,Dependency Injection,Asp.net Core,关于如何在ConfigureServicesServiceCollection服务中注入数据保护,我在这里有点困惑,因为用户设置也是从services.ConfigureConfiguration.GetSectionUserSettings;注入的 下面的appsettings_json中的appName_和appsettings_json中的dirInfo_值应该来自注入的usersettings配置,并且可以通过注入IOptions在其他任何地方访问,但不能在此处访问 public voi

关于如何在ConfigureServicesServiceCollection服务中注入数据保护,我在这里有点困惑,因为用户设置也是从services.ConfigureConfiguration.GetSectionUserSettings;注入的

下面的appsettings_json中的appName_和appsettings_json中的dirInfo_值应该来自注入的usersettings配置,并且可以通过注入IOptions在其他任何地方访问,但不能在此处访问

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

您还可以使用extension方法.Bind。此方法将尝试通过匹配配置中的键将值绑定到配置对象

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

谢谢,我想这比我现在从服务提供程序中提取UserSettings配置var userSettingsConfig=services.BuildServiceProvider.GetServices.First;要好;。我明天试试看。
// 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);