ASP.NET Core—access Configuration from static class

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

    I just created below class:

    
        /// 
        /// 
        /// 
        public static class ConfigurationManager
        {
            /// 
            /// 
            /// 
            public sealed class ConfigurationManagerAppSettings
            {
                /// 
                /// 
                /// 
                internal ConfigurationManagerAppSettings() { }
    
                /// 
                /// 
                /// 
                /// 
                /// 
                public string this[string key] => (TheConfiguration ?? throw new Exception("Set ConfigurationManager.TheConfiguration in Startup.cs")).GetSection($"AppSettings:{key}").Value;
            }
    
            /// 
            /// 
            /// 
            public static IConfiguration? TheConfiguration { get; set; }
    
            /// 
            /// 
            /// 
            public static readonly ConfigurationManagerAppSettings AppSettings = new ConfigurationManagerAppSettings();
        }
    

    and below code:

    public class Startup
        {
            public Startup(IConfiguration configuration) {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services) {
                ConfigurationManager.TheConfiguration = Configuration;
    
    

提交回复
热议问题