如何将 appsetting.json 配置文件中的 IConfiguration 注入到他的代码中?

How to inject IConfiguration from appsetting.json config file into his code?

看了官方文档here我还是不明白如何加载和使用这些appsetting.json配置文件。从理论上讲,一切似乎都是合乎逻辑的,但是当我尝试在 class 中设置它时,我遇到了问题。

让我先给你我的部分代码。对于那些我知道我在 IndentityServer4 实现中这样做的人,但我需要在我的 API 和客户端中做同样的事情。

我修改了 Program.cs 文件以包含这种加载配置文件的新方法,如文档中所述:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.SetBasePath(Directory.GetCurrentDirectory());
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
                })
                .UseStartup<Startup>();
    }

我在 Statup.cs

中没有做任何与配置相关的事情
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddIdentityServer()
                .AddDeveloperSigningCredential(persistKey: false)
                .AddTestUsers(Config.GetUsers())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }

最后是我的 Config.cs,或者我的配置文件的一部分。这是我想使用我的配置的这个。比方说,为了简单起见,我想从我的配置文件中加载我所有的字符串。

    public static class Config
    {
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>()
            {
                new Client
                {
                    ClientName = "xxxxxxxx",
                    ClientId = "f26ee5d6-xxxx-xxxx-xxxx-xxxx0efa43d9.local.app",
                    AllowedGrantTypes = GrantTypes.Code,
                    AllowOfflineAccess = true,
                    IdentityTokenLifetime = 60 * 60 * 24,
                    AccessTokenLifetime = 60 * 60 * 24,
                    RedirectUris = new List<string>()
                    {
                        "https://www.getpostman.com/oauth2/callback"
                    },
                    PostLogoutRedirectUris = new List<string>()
                    {
                        "https://www.getpostman.com"
                    },
                    AllowedCorsOrigins = new List<string>()
                    {
                        "https://www.getpostman.com"
                    },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "xxxxxx",
                    },
                    ClientSecrets = new List<Secret>
                    {
                        new Secret("XXXXXXXX".Sha256())
                    },
                    AllowAccessTokensViaBrowser = true,
                    RequireConsent = false,
                    EnableLocalLogin = true,
                    Enabled = true
                }
             };

        }
    }

您可能注意到我的 config.cs 是静态的,并且可能由我无法处理的代码加载。所以我不知道如何"inject"这里配置。

创建映射到您的设置的强类型对象模型

public class MySettings {
    //Properties here
}

IConfiguration 注入 Startup

private IConfiguration configuration;
public Startup(IConfiguration configuration) {
    this.configuration = configuration;
}

使用配置绑定到对象模型并将其显式注入依赖方法

public void ConfigureServices(IServiceCollection services) {

    MySettings settings = configuration.GetSection("Section_Name_Here").Get<MySettings>();

    services.AddMvc();
    services.AddIdentityServer()
        .AddDeveloperSigningCredential(persistKey: false)
        .AddTestUsers(Config.GetUsers())
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients(settings)); //<--
}

相关方法会相应重构的地方

public static IEnumerable<Client> GetClients(MySettings settings) {
    return new List<Client>() {
        new Client {
            ClientName = settings.ClientName,

            //...omitted for brevity