Best Practices for Loading Custom Settings in .NET Core
Roel
Posted on June 1, 2023
Intro
In .NET Core, configuration data is typically stored in the appsettings.json file. This file is a flexible and easy-to-use solution for storing settings that can be changed without modifying the application's code. In this post, we'll explore how to create custom configuration settings and access them using dependency injection.
Creating Custom Configuration Settings
Let's say we have some custom settings in the appsettings.json file. For example, we'll create a section named CustomSettings:
{
"CustomSettings": {
"Setting1": "Value1",
"Setting2": "Value2"
}
}
Defining a Configuration Class
Next, we'll create a class in our .NET Core application that matches the structure of our custom settings:
public class CustomSettings
{
public string Setting1 { get; set; }
public string Setting2 { get; set; }
}
Registering the Configuration Class
Now, we'll register our CustomSettings class in the Program.cs file so that it can be injected into other classes:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CustomSettings>(Configuration.GetSection("CustomSettings"));
// ...
}
In this code, Configure tells .NET Core to create an instance of CustomSettings and populate it with the values from the CustomSettings section of the appsettings.json file.
Injecting the Configuration Class
Finally, we can inject IOptions<CustomSettings>
into any class where we want to access our custom settings:
public class MyService
{
private readonly CustomSettings _settings;
public MyService(IOptions<CustomSettings> settings)
{
_settings = settings.Value;
}
public void DoSomething()
{
string setting1 = _settings.Setting1;
// ...
}
}
In this code, IOptions is a wrapper that provides access to our CustomSettings instance. We can access the CustomSettings instance itself through the Value property.
Posted on June 1, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024