我在手动构造一个IServiceProvider
时遇到了麻烦,它将允许我的单元测试使用它来使用GetService<IOptions<MyOptions>>
引入共享测试配置
我创建了一些单元测试来说明我的问题,如果可以用于回答问题,则此存储库也可以是found here。
JSON
{
"Test": {
"ItemOne": "yes"
}
}
选项类
public class TestOptions
{
public string ItemOne { get; set; }
}
测试
在这些测试中,
ConfigureWithBindMethod
和ConfigureWithBindMethod
均失败,并且SectionIsAvailable
通过。因此,据我所知,该部分正按预期从JSON文件中使用。[TestClass]
public class UnitTest1
{
[TestMethod]
public void ConfigureWithoutBindMethod()
{
var collection = new ServiceCollection();
var config = new ConfigurationBuilder()
.AddJsonFile("test.json", optional: false)
.Build();
collection.Configure<TestOptions>(config.GetSection("Test"));
var services = collection.BuildServiceProvider();
var options = services.GetService<IOptions<TestOptions>>();
Assert.IsNotNull(options);
}
[TestMethod]
public void ConfigureWithBindMethod()
{
var collection = new ServiceCollection();
var config = new ConfigurationBuilder()
.AddJsonFile("test.json", optional: false)
.Build();
collection.Configure<TestOptions>(o => config.GetSection("Test").Bind(o));
var services = collection.BuildServiceProvider();
var options = services.GetService<IOptions<TestOptions>>();
Assert.IsNotNull(options);
}
[TestMethod]
public void SectionIsAvailable()
{
var collection = new ServiceCollection();
var config = new ConfigurationBuilder()
.AddJsonFile("test.json", optional: false)
.Build();
var section = config.GetSection("Test");
Assert.IsNotNull(section);
Assert.AreEqual("yes", section["ItemOne"]);
}
}
指出可能很有用
在立即窗口中调用
config.GetSection("Test")
时,我得到了这个值{Microsoft.Extensions.Configuration.ConfigurationSection}
Key: "Test"
Path: "Test"
Value: null
从表面上看,我本以为Value不应为null,这使我认为我可能在这里遗漏了一些明显的东西,因此,如果有人能发现我在做错的事情,那将是天才。
谢谢!
最佳答案
要在服务集合中使用选项,您需要添加使用选项collection.AddOptions();
所需的服务
这应该可以解决问题:
[TestMethod]
public void ConfigureWithoutBindMethod()
{
var collection = new ServiceCollection();
collection.AddOptions();
var config = new ConfigurationBuilder()
.AddJsonFile("test.json", optional: false)
.Build();
collection.Configure<TestOptions>(config.GetSection("Test"));
var services = collection.BuildServiceProvider();
var options = services.GetService<IOptions<TestOptions>>();
Assert.IsNotNull(options);
}
关于.net - 即使GetSection正在运行,ServiceCollection也会为IOptions返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019988/