ASP.NET Core—access Configuration from static class

后端 未结 13 2008
我在风中等你
我在风中等你 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:58

    You can use Signleton pattern to access your configurations from anywhere

        public class ConnectionStrings
        {
            private ConnectionStrings()
            {
            }
            // property with getter only will not work.
            public static ConnectionStrings Instance { get; protected set; } = new ConnectionStrings();
    
            public string DatabaseConnection { get; set; }
        }
    

    and in your startup class

        public class Startup
        {
            private readonly IConfiguration configuration;
    
            public Startup(IConfiguration configuration)
            {
                this.configuration = configuration;
                configuration.GetSection("ConnectionStrings").Bind(ConnectionStrings.Instance);
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
            }
    
            public void Configure(IApplicationBuilder app)
            {
            }
        }
    
    0 讨论(0)
提交回复
热议问题