ASP.NET Core—access Configuration from static class

后端 未结 13 2234
我在风中等你
我在风中等你 2021-02-01 00:27

I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an e

13条回答
  •  渐次进展
    2021-02-01 00:33

    I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:

    public class Program
    {
        public static IConfigurationRoot Configuration { get; set; }
        public static void Main(string[] args = null)
        {
            var builder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
    
            Configuration = builder.Build();
    
            Console.WriteLine($"option1 = {Configuration["option1"]}");
    
            // Edit:
            IServiceCollection services = new ServiceCollection();
            services.AddOptions();
            services.Configure(_configuration.GetSection("HelloWorld"));
            // And so on...
        }
    }
    

提交回复
热议问题