How do I access Configuration in any class in ASP.NET Core?

前端 未结 11 1707
梦如初夏
梦如初夏 2020-11-29 01:09

I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.

Below is Startup.c

11条回答
  •  旧时难觅i
    2020-11-29 01:37

    I looked into the options pattern sample and saw this:

    public class Startup
    {
        public Startup(IConfiguration config)
        {
            // Configuration from appsettings.json has already been loaded by
            // CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
            // the configuration into the Configuration property.
            Configuration = config;
        }
    ...
    }
    

    When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.

    Example:

    public class MyClass{
    
        private Iconfiguration _config;
    
        public MyClass(Iconfiguration config){
            _config = config;
        }
    
        ... // access _config["myAppSetting"] anywhere in this class
    }
    

提交回复
热议问题