简体   繁体   English

ASP.NET 5(vNext) - 获取配置设置

[英]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. 我正在编写一个基本的应用程序来学习ASP.NET 5.我觉得困惑的一个领域是配置。 Prior to ASP.NET 5, I could do the following: 在ASP.NET 5之前,我可以执行以下操作:

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: 现在,在vNext世界中,我有一个如下所示的config.json文件:

config.json config.json

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

Then in Startup.cs, I have the following: Startup.cs 然后在Startup.cs中,我有以下内容: 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. 我在/src/Website/Code/Models/MyClass.cs中有MyClass.cs。

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"? 如何获得“AppSettings:SomeKey”的值?

ASP.NET 5 makes heavy use of Dependency Injection, so if you are also using Dependency Injection then this is very simple. ASP.NET 5大量使用依赖注入,所以如果你也使用依赖注入,那么这很简单。 If you examine the sample MVC6 project, you can see how this works: 如果您检查示例MVC6项目,您可以看到它是如何工作的:

First, there's a class AppSettings defined in Properties, which is a strongly-typed version of the options your class supports. 首先,在属性中定义了一个类AppSettings,它是您的类支持的选项的强类型版本。 In the sample project, this just contains SiteTitle. 在示例项目中,它只包含SiteTitle。

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

Then, this class is initialised through dependency injection in ConfigureServices. 然后,通过ConfigureServices中的依赖注入初始化此类。 Configuration here is the one you created in the constructor of the Startup class. 这里的Configuration是您在Startup类的构造函数中创建的Configuration

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. 然后,假设您的类由依赖注入容器实例化,您可以简单地请求IOptions,然后您将获得一个。 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;
    }
}

I use ASP.NET 5 dependency injection, like so. 我使用ASP.NET 5依赖注入,就像这样。

config.json: config.json:

{
    "random":  "Hello World!"
}

startup.cs: startup.cs:

public class Startup
{
    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json");

        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton<IConfiguration>(sp => { return Configuration; });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc(routes =>
        {
            routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
        });

    }

}

Controller: 控制器:

public class HomeController : Controller
{

    IConfiguration config;

    public HomeController(IConfiguration config)
    {
        this.config = config;
    }

    public IActionResult Index()
    {
        var template = "<marquee>{0}</marquee>";
        var content = string.Format(template, config.Get("random"));
        return Content(content, "text/html");
    }
}

I highly recommend using the OptionsModel instead of reading the configuration directly. 我强烈建议使用OptionsModel而不是直接读取配置。 It allows strong typed model binding to configuration. 它允许强类型模型绑定到配置。

Here is an example: GitHub.com/aspnet/Options/test/Microsoft.Extensions.Options.Test/OptionsTest.cs 下面是一个示例: GitHub.com/aspnet/Options/test/Microsoft.Extensions.Options.Test/OptionsTest.cs

For your particular case create a model: 对于您的特定情况,创建一个模型:

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

and then bind it to your configuration: 然后将其绑定到您的配置:

var config = // The configuration object
var options = ConfigurationBinder.Bind<AppSettings>(config); 
Console.WriteLine(options.SomeSetting);

That way you don't have to worry from where the setting comes from, how it is stored or what is the structure. 这样您就不必担心设置的来源,存储方式或结构。 You simply predefine your options model and magic happens. 您只需预定义您的选项模型并发生魔术。

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. 如果你需要其他类中的值,你应该将其注入.ASP.NET已内置依赖注入,但如果你只需要一个MyClass实例,你可以新建它而不是设置一个DI容器。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM