如何在ASP.NET Core 的任意类中注入Configuration

遇到的问题
我已经通读了 MSDN 上关于 Configuration 的相关内容,文档说可实现在 application 的任意位置访问 Configuration .

下面是 Startup.cs 的模板代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
 
        if (env.IsEnvironment("Development"))
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
 
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }
 
    public IConfigurationRoot Configuration { get; }
 
    // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
 
        services.AddMvc();
    }
 
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
 
        app.UseApplicationInsightsRequestTelemetry();
 
        app.UseApplicationInsightsExceptionTelemetry();
 
        app.UseMvc();
    }
}
我知道可以通过 DI 的方式将 Configuration 注入到 Controller,Service,Repository 等地方,但在真实项目中,会有很多类是在这三块之外的。

请问我如何在这三大块之外实现 Configuration 的注入呢?换句话说:可以在任意类中实现 Configuration 的注入...

上一篇:4.Kotlin的泛型和委托


下一篇:Java中的四种权限修饰符