Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

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

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 settingValue = ConfigurationManager.AppSettings["SomeKey"];

I would have lines of code like that sprinkled throughout my code. Now, in the vNext world, I have a config.json file that looks like this:

config.json

{
  "AppSettings": {
    "SomeKey":"SomeValue"
  }
}

Then in Startup.cs, I have the following: Startup.cs

public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment) 
{
  Configuration = new Configuration()
      .AddJsonFile("config.json");
}

From there, I'm totally stumped. I have MyClass.cs in /src/Website/Code/Models/MyClass.cs.

MyClass.cs

public class MyClass
{
  public string DoSomething() 
  {
    var result = string.Empty;
    var keyValue = string.Empty; // TODO: What do I do here? How do I get the value of "AppSettings:SomeKey"?
    return result;
  }
}

How do I get the value of "AppSettings:SomeKey"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ASP.NET 5 makes heavy use of Dependency Injection, so if you are also using Dependency Injection then this is very simple. If you examine the sample MVC6 project, you can see how this works:

First, there's a class AppSettings defined in Properties, which is a strongly-typed version of the options your class supports. In the sample project, this just contains SiteTitle.

public class AppSettings
{
    public string SiteTitle { get; set; }
}

Then, this class is initialised through dependency injection in ConfigureServices. Configuration here is the one you created in the constructor of the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
    // ...
}

Then, assuming your class is instantiated by the dependency injection container, you can simply ask for an IOptions and you'll get one. For example, in a controller you could have the following:

public class HomeController
{
    private string _title;
    public HomeController(IOptions<AppSettings> settings) 
    {
        _title = settings.Options.SiteTitle;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...