在ASP.NET Core 2中,我有以下使用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我注册选项如下
services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));
dotnet能够将IOptions<MyOptions>
注入MyService类。
现在,我有集成测试项目。我已将相同的appsettings.json复制到集成测试项目中。我想创建加载来自appsettings.json
的值的IOptions<MyOptions>
实例
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。
答案 0 :(得分:3)
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);