简体   繁体   English

在ASP.net Core 2中管理设置

[英]Managing Settings in ASP.net Core 2

I am converting an MVC 5 application to Core 2, and am confused over the settings. 我将MVC 5应用程序转换为Core 2,并对设置感到困惑。

I have a service that connects to an API server; 我有一个连接到API服务器的服务; The API server address is stored in a AppSettings.json configuration file as there is a development and production version. 由于存在开发和生产版本,因此API服务器地址存储在AppSettings.json配置文件中。

"EtimeSettings": {
    "Api_Server": "123.123.123.123"
}

Having read some blogs, I have added the following code to startup.cs ConfigureServices : 阅读了一些博客后,我将以下代码添加到了startup.cs ConfigureServices

services.AddMvc();

var eTimeSettings = new EtimeSettingsModel();
Configuration.Bind("EtimeSettings", eTimeSettings);
services.AddSingleton(eTimeSettings);

设置图片

I cannot figure out how to retrieve these values in my API Service. 我无法弄清楚如何在我的API服务中检索这些值。

I was though able to retrieve the values using the following code; 我虽然可以使用以下代码检索值;

public string GetApiServer()
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");

    EtimeSettingsModel et = new EtimeSettingsModel();
    IConfiguration Configuration = builder.Build();
    Configuration.GetSection("EtimeSettings").Bind(et);
    var apiServer = Configuration["EtimeSettings:Api_Server"];
    return apiServer;
}

But I really don't believe that this is the best way. 但是我真的不相信这是最好的方法。

What am I missing? 我想念什么?

Referencing Options pattern in ASP.NET Core Documentation ASP.NET Core文档中的引用选项模式

Assuming 假设

public class EtimeSettingsModel {
    public string Api_Server { get; set; }
}

To setup the IOptions<TOptions> service you call the AddOptions extension method during startup in your ConfigureServices method. 若要设置IOptions<TOptions>服务,请在启动时在ConfigureServices方法中调用AddOptions扩展方法。 You configure options using the Configure<TOptions> extension method. 您可以使用Configure<TOptions>扩展方法配置选项。 You can configure options using a delegate or by binding your options to configuration: 您可以使用委托或通过将选项绑定到配置来配置选项:

public void ConfigureServices(IServiceCollection services) {

    //...

    // Setup options with DI
    services.AddOptions();

    // Configure EtimeSettingsModel using config by installing 
    // Microsoft.Extensions.Options.ConfigurationExtensions
    // Bind options using a sub-section of the appsettings.json file.
    services.Configure<EtimeSettingsModel>(Configuration.GetSection("EtimeSettings"));

    services.AddMvc();

    //...       
}

Options can be injected into your application using the IOptions<TOptions> accessor service. 可以使用IOptions<TOptions>访问器服务将选项注入到您的应用程序中。

private readonly EtimeSettingsModel eTimeSettings;
public MyAPIService(IOptions<EtimeSettingsModel> eTimeSettings) {
    this.eTimeSettings = eTimeSettings.Value;
}

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

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