ASP.NET 5 (vNext) - Getting a Configuration Setting

前端 未结 4 1734
别那么骄傲
别那么骄傲 2020-12-05 12:52

I\'m writing a basic app to learn ASP.NET 5. One area I find very confusing is configuration. Prior to ASP.NET 5, I could do the following:

var sett         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 13:37

    Use this:

    var value = Configuration.Get("AppSettings:SomeKey");
    

    Based on this blog post. The colon is similar to dot notation and is used for navigation down the hierarchy.

    If you need the value in other classes, you should inject it in. ASP.NET has built in dependency injection, but if you just need one instance of MyClass you can new it up instead of setting up a DI container.

    public IConfiguration Configuration { get; set; }
    
    public Startup(IHostingEnvironment environment) 
    {
        Configuration = new Configuration()
          .AddJsonFile("config.json");
        //generally here you'd set up your DI container. But for now we'll just new it up
        MyClass c = new MyClass(Configuration.Get("AppSettings:SomeKey"));
    }
    
    public class MyClass
    {
        private readonly string Setting; //if you need to pass multiple objects, use a custom POCO (and interface) instead of a string.
    
        public MyClass(string setting) //This is called constructor injection
        {
            Setting = setting;
        }
    
        public string DoSomething() 
        {
            var result = string.Empty;
            //Use setting here
            return result;
        }
    }
    

提交回复
热议问题