Core中获取IConfiguration实例

Core中获取IConfiguration实例

本文介绍了如何在ASP.NET Core中获取IConfiguration实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个单元测试项目来测试我的webapi,我需要初始化一个控制器,问题是在构造函数中它接收到一个IConfiguration,它是由依赖注入提供的并且可以正常工作。

I making a unittesting project to test my webapi and i need to initialize a controller the problem is that in the constructor it receive a IConfiguration that it is provide by dependency-injection and works fine.

但是当我想手动初始化它时,我没有办法获取此实例。

But when I want to initialize it manually i have not way to get this instance.

我正在尝试从单元测试项目中初始化它

I am trying to initialize it from a unittest project no inside of the same project.

控制器看起来像:

public Controller(IConfiguration configuration) { _configuration = configuration; }


推荐答案

我可能应该从以下语句开始在.Net Core应用程序中,您不应将 IConfiguration 的实例传递给控制器​​或其他类。您应该使用通过 IOptions< T> 注入的强类型设置。有关更多详细信息,请参见本文:。

I'd probably should start from the statement that in .Net Core application you should not pass instance of IConfiguration to your controllers or other classes. You should use strongly typed settings injected through IOptions<T>. See this article for more details: Options pattern in ASP.NET Core.

使用选项模式时,将具有控制器所需设置的POCO。然后将此设置对象注入包装在 IOptions< T> 中的控制器中:

When using options pattern, you will have POCO for the settings required by a controller. This settings object is then injected into controller wrapped into IOptions<T>:

public class ControllerSettings
{
    public string Setting1 { get; set; }

    public int Setting2 { get; set; }

    // ...
}

public class Controller
{
    private readonly ControllerSettings _settings;

    public Controller(IOptions<ControllerSettings> options)
    {
        _settings = options.Value;
    }
}

然后,通过您想要的任何设置都非常简单单元测试。只需填写设置实例并使用任何可用的模拟框架(例如IOptions< T> / rel = noreferrer>起订量或:

Then it's pretty simple to pass any settings you want from a Unit Test. Just fill settings instance and wrap to IOptions<T> with any of available mocking frameworks, like Moq or NSubstitute:

[TestMethod]
public void SomeTest()
{
    var settings = new ControllerSettings
    {
        Setting1 = "Some Value",
        Setting2 = 123,
    };

    var options = new Mock<IOptions<ControllerSettings>>();
    options.Setup(x => x.Value).Returns(settings);

    var controller = new Controller(options.Object);

    //  ...
}

有时是必需的在开发集成测试时使用项目的实际配置。在这种情况下,您可以创建 ConfigurationBuilder 的实例,并用与测试代码中相同的配置源填充它:

Sometimes it's required to use real configuration of the project, for example when developing integration test. In this case you could create instance of ConfigurationBuilder and fill it with the same configuration sources as in tested code:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// Duplicate here any configuration sources you use.
configurationBuilder.AddJsonFile("AppSettings.json");
IConfiguration configuration = configurationBuilder.Build();

这篇关于如何在ASP.NET Core中获取IConfiguration实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:54