当前位置 : 主页 > 编程语言 > c语言 >

c# – 如何在ASP.NET Core中的任何类中访问Configuration?

来源:互联网 收集:自由互联 发布时间:2021-06-25
我在ASP.NET核心上经历了 configuration documentation.文档说您可以从应用程序的任何位置访问配置. 下面是模板创建的Startup.cs public class Startup{ public Startup(IHostingEnvironment env) { var builder = new C
我在ASP.NET核心上经历了 configuration documentation.文档说您可以从应用程序的任何位置访问配置.

下面是模板创建的Startup.cs

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

所以在Startup.cs中我们配置了所有设置,Startup.cs也有一个名为Configuration的属性

我无法理解您如何在控制器或应用程序中的任何位置访问此配置? MS建议使用options pattern,但我只有4-5个键值对,所以我不想使用选项模式.我只想访问应用程序中的Configuration.如何在任何课程中注入它?

更新

使用ASP.NET Core 2.0将automatically在依赖注入容器中添加应用程序的IConfiguration实例.这也与WebHostBuilder上的ConfigureAppConfiguration结合使用.

例如:

public static void Main(string[] args)
{
    var host = WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder =>
        {
            builder.AddIniFile("foo.ini");
        })
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

就像在ConfigurationServices中将IConfiguration实例作为单个对象添加到服务集合一样简单:

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IConfiguration>(Configuration);

   // ...
}

Configuration是Startup类中的实例.

这允许您在任何控制器或服务中注入IConfiguration:

public class HomeController
{
   public HomeController(IConfiguration configuration)
   {
      // Use IConfiguration instance
   }
}
网友评论