DEV Community

Roel
Roel

Posted on

Best Practices for Loading Custom Settings in .NET Core

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

Enter fullscreen mode Exit fullscreen mode

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; }
}
Enter fullscreen mode Exit fullscreen mode

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"));
    // ...
}
Enter fullscreen mode Exit fullscreen mode

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;
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)