An easy and typesafe way to use configuration values in your .NET core applications is through IOptions<T>.
This allows you to create a settings section in your appsettings.json:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"MySettings": { | |
"ApplicationName": "SampleApp", | |
"Environment": "Test" | |
} | |
} |
And then map this to a specific class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MySettings | |
{ | |
public string ApplicationName{get;set;} | |
public string Environment{get;set;} | |
} |
The only thing you need to do is to specify the section in your Startup.cs:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.Configure<MySettings>(Configuration.GetSection("MySettings")); | |
} |
Now you can inject these settings in your code through IOptions<T>:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExampleRepository : IExampleRepository | |
{ | |
private readonly MySettings _mySettings; | |
public ExampleRepository(IOptions<MySettings> options) | |
{ | |
_mySettings = options.Value; | |
} | |
} |
But what if you want to unit test this class? How can you create an IOptions<T> instance?
A solution exists through the Options.Create() method:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mySettings = Options.Create(new MySettings | |
{ | |
ApplicationName = "Example App", | |
Environment = "test" | |
}); | |
var exampleRepository = new ExampleRepository(mySettings); |