微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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 的注入...

原文地址:https://blog.csdn.net/buduoduoorg/article/details/117214532

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐