How to get an instance of IConfiguration in asp.net core?

27,164

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.

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;
    }
}

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);

    //  ...
}

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();
Share:
27,164

Related videos on Youtube

Rabel Obispo
Author by

Rabel Obispo

Full-stack developer Love coding! I try to find the best way do things. And most important I make things happen.

Updated on April 09, 2020

Comments

  • Rabel Obispo
    Rabel Obispo about 4 years

    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.

    The controller looks like:

    public Controller(IConfiguration configuration) { _configuration = configuration; }
    
  • user3885927
    user3885927 over 5 years
    What namespace is the ConfigurationBuilder from?
  • user3885927
    user3885927 over 5 years
    Found it, it's Microsoft.Extensions.Configuration.Json