How to load appsetting.json section into Dictionary in .NET Core?

后端 未结 10 1489
误落风尘
误落风尘 2020-12-05 16:49

I am familiar w/ loading an appsettings.json section into a strongly typed object in .NET Core startup.cs. For example:

public class CustomSection 
{
   publ         


        
10条回答
  •  伪装坚强ぢ
    2020-12-05 17:48

    For simple (perhaps microservice) applications you can just add it it as a singleton Dictionary and then inject it wherever you need it:

    var mobileConfig = Configuration.GetSection("MobileConfigInfo")
                        .GetChildren().ToDictionary(x => x.Key, x => x.Value);
    
    services.AddSingleton(mobileConfig);
    

    And the usage:

    public class MyDependantClass
    {
        private readonly Dictionary _mobileConfig;
    
        public MyDependantClass(Dictionary mobileConfig)
        {
            _mobileConfig = mobileConfig;
        }
    
        // Use your mobile config here
    }
    

提交回复
热议问题