即使GetSection正在运行,ServiceCollection也会为IOptions返回null

Chr*_*ris 4 .net .net-core

我在手动构造一个时遇到了麻烦IServiceProvider,它将允许我的单元测试使用它来引入共享的测试配置GetService<IOptions<MyOptions>>

我创建了一些单元测试来说明我的问题,如果可以用于回答问题,也可以在此处找到该代码的存储库。

JSON

{
  "Test": {
    "ItemOne":  "yes"
  }
}
Run Code Online (Sandbox Code Playgroud)

期权类别

public class TestOptions
{
    public string ItemOne { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

测试

这些测试都失败了,ConfigureWithBindMethod并且ConfigureWithBindMethodSectionIsAvailable合格了。因此,据我所知,该部分正按预期从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"]);
    }
}
Run Code Online (Sandbox Code Playgroud)

可能有用的指出

config.GetSection("Test")在立即窗口中调用时,我得到了这个值

{Microsoft.Extensions.Configuration.ConfigurationSection}
    Key: "Test"
    Path: "Test"
    Value: null
Run Code Online (Sandbox Code Playgroud)

从表面上看,我本以为Value不应为null,这使我认为我可能在这里遗漏了一些明显的东西,因此,如果有人能发现我在做错的事情,那将是天才。

谢谢!

klo*_*eek 7

要使用服务集合中的选项,您需要添加使用选项所需的服务 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);
}
Run Code Online (Sandbox Code Playgroud)

  • @Dave,您需要包 Microsoft.Extensions.Options.ConfigurationExtensions (4认同)