本文介绍了如何构建IOptions< T>用于检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Core 2中,我有一个采用 IOptions< T>

In ASP.NET Core 2 i have the following class that takes IOptions<T>

public class MyOptions
{
    public string Option1 { get; set; }
    public string Option2 { get; set; }
}


public class MyService:IMyService
{
  private readonly MyOptions _options;
  public MyService(IOptions<MyOptions> options)
  {
    _options = options.Value;
  }
}

appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },  
  "MyOptions": {
    "Option1": "option 1 value",
    "Option2": "option 2 value"
  }
}

然后在startup.cs中,我注册了以下选项

Then i startup.cs i register options as below

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

dotnet能够注入 IOptions< MyOptions> 进入MyService类。

dotnet is able to inject IOptions<MyOptions> into MyService class.

现在,我有集成测试项目。并且我已经将相同的appsettings.json复制到集成测试项目中。我想创建 IOptions< MyOptions> 的实例,该实例从appsettings.json中加载值

Now, i have integration test project. and i have copied the same appsettings.json into integration test project. I want to create instance of IOptions<MyOptions> that loads the values from appsettings.json

public class MyTestClass
{
    private readonly IConfigurationRoot _config;

    public MyTestClass()
    {                        
        _config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
    }

    [Fact]
    public void MyTest()
    {
        // arrange

        // this line returns NULL
        var optionValue  = _config.GetSection("MyOptions").Value;

        // i also tried GetValue which returns NULL as well
        //var optionValue = _config.GetValue<MyOptions>("MyOptions");

        var options = Options.Create<MyOptions>(optionValue);
        var service = new MyService(options);

        //act

        // assert
    }
}

_config.GetSection( MyOptions)。Value _config.GetValue< MyOptions>( MyOptions )均返回null。

_config.GetSection("MyOptions").Value and _config.GetValue<MyOptions>("MyOptions") both returns null.

当我快速查看 _config 变量时,我看到值是从appsettings.json
中加载的

when i do quick watch on _config variable i see the values are loaded from appsettings.json

推荐答案

找到了它。我必须绑定实例

found it. i have to bind the instance

var optionValue  = new MyOptions();
_config.GetSection("MyOptions").Bind(optionValue);
 var options = Options.Create<MyOptions>(optionValue);

或者我也可以这样做

 var optionValue = _config.GetSection("MyOptions").Get<MyOptions>();
 var options = Options.Create<MyOptions>(optionValue);

这篇关于如何构建IOptions&lt; T&gt;用于检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 20:28