访问 IOptions<T> 对象 .NET Core



我是.NET Core的新手,所以如果这是一个新手问题,我深表歉意。我使用 VS 2017 在 .NET Core 2 中创建了一个 Web API 项目。

对我来说,我有appsettings.json带有一些连接设置的文件。

在阅读了微软教程中的IOptions<T>后,我正在做如下的事情:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<MyOptions>(Configuration);
    // I want to access MyOptions object here to configure other services?how do i do that?
    service.AddHangfire( // Get MyOptions.HangfireConenctionString etc.)
}

如何在ConfigureServices中访问创建的MYOptions对象,以及是否需要Configure(IApplicationBuilder app,..)方法访问它?

我只在教程中看到控制器中注入IOptions<T>的示例。

在 中使用某些设置

public void ConfigureServices(IServiceCollection services)
{
    // Load the settings directly at startup.
    var settings = Configuration.GetSection("Root:MySettings").Get<MySettings>();
    // Verify mailSettings here (if required)
    service.AddHangfire(
        // use settings variable here
    );
    // If the settings needs to be injected, do this:
    container.AddSingleton(settings);
}

如果您需要在应用程序组件中使用配置对象,请不要将IOptions<T>注入到组件中,因为这只会导致不可原谅的缺点,如此处所述。而是直接注入值,如以下示例所示。

public class HomeController : Controller  
{
    private MySettings _settings;
    public HomeController(MySettings settings)
    {
        _settings = settings;
    }
}

你很接近

services.Configure<MyOptions>(options => Configuration.GetSection("MyOptions").Bind(options));

现在,您可以使用依赖关系注入访问"我的选项"

public class HomeController : Controller  
{
    private MySettings _settings;
    public HomeController(IOptions<MySettings> settings)
    {
        _settings = settings.Value
        // _settings.StringSetting == "My Value";
    }
}

我从这篇优秀的文章中摘取了片段:安德鲁·洛克的 https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/。

这取决于您的appsettings.json以及您如何命名该部分。例如:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "MySettings": {
    "ConnectionString": "post.gres:39484"
  }
}

在这里,该部分的名称是"我的设置"。通常,在我的Startup.cs ASP.NET Core 2.2中,我使用类似的东西:

services.AddOptions();
services.Configure<MyOptions>(Configuration.GetSection("MySettings"));

但是这样的东西也有效:

services.AddOptions();
services.AddOptions<MyOptions>().Bind(Configuration.GetSection("MySettings"));

如果已将程序配置为使用 AddEnvironmentVariables() ,则还可以通过添加名为 MySettings__ConnectionString 的配置变量来设置设置。该值可以来自多个位置。

如果要验证选项类,则可能需要使用数据批注。

最新更新