avatarColton

Summary

The web content discusses the use of the Options Pattern in .NET for managing configuration data, emphasizing its benefits in encapsulation and separation of concerns through strongly-typed configuration classes.

Abstract

The Options Pattern in .NET is presented as a robust method for handling configuration settings in applications. It allows for the creation of strongly-typed classes that represent sections of the configuration, which can be injected into components via dependency injection. This approach enhances maintainability by encapsulating configuration settings and adhering to the principle of separation of concerns. The pattern is particularly useful for complex and deeply nested configuration structures. The content also explains how to register and use these configuration classes with different interfaces like IOptions, IOptionsSnapshot, and IOptionsMonitor, each suited for different scenarios regarding the lifetime and reloading capabilities of the configuration data.

Opinions

  • The Options Pattern is favored for its ability to manage configuration data in a clean and maintainable way.
  • Using IOptions is recommended over manual binding for its convenience and integration with dependency injection.
  • The author suggests that IOptionsSnapshot and IOptionsMonitor are preferable when configuration changes need to be re-read during the application's lifetime.
  • The article implies that the Options Pattern aligns well with software engineering principles such as encapsulation and separation of concerns.
  • The use of strongly-typed classes for configuration is seen as a significant advantage for developers to avoid errors and improve code readability.

.NET | Working With Options Pattern

Another way to read data from the configuration data

Photo by Rima Kruciene on Unsplash

Options Pattern Introduction

Options pattern is a flexible configuration data management way that enables us to use strongly typed configurations. It uses classes to bind groups of related configurations. We can inject these classes via dependency injection with IOptions<T> to include only the part that we need.

This pattern satisfies two main and important software engineering principles.

  • Encapsulation: these classes only depend on the configuration settings that they use
  • Separation of Concerns: Settings for different parts of the app aren’t depending on one another

If you’ve missed how to configure the settings, check out here:

Why Use IOptions Pattern

For example, let’s assume that we have some configuration settings in the appSettings.json

{
  ...

  "Jwt": {
    "Issuer": "thisisyourissuers",
    "SigningKey": "thiskeyisveryhardtobreak",
    "IsValidateLifetime": true
  },

  ...
}

For reading the Issuer , we can directly access its value by using the classic IConfiguration instance, which is already automatically registered into the dependency injection container since ASP.NET Core 2.0.

We can directly use it through:

public class HomeController
{
   public HomeController(IConfiguration configuration)
   {
      // Use IConfiguration instance
      var issuer = configuration["Jwt:Issuer"]
   }
}

This way will become extremely hard to maintain when the structure of the configuration goes diverse with deeply nested sections.

Instead, we can create a “strongly-typed” class to sections in the configuration to separate the concerns and make it easy to access and maintain.

Back in our example, our strongly typed class for the Jwt section can be as below:

public class JwtOptions 
{
  public string Issue {get; set;}
  public string SigningKey {get; set;}
  public bool IsValidateLifetime {get; set;}
}

We need to ensure that the property names and types must match the key names and values exactly in the configuration file.

The next step is to register this class into the dependency injection container so that we can use it in other areas, like services or controllers.

One approach is to use the bind method. We can manually create an instance of this class and bind it to the configuration section of the JSON file.

# Startup.ConfigureServices() Method #

JwtOptions jwtOptions = new();        Configuration.GetSection("Jwt").Bind(jwtOptions);        services.AddSingleton(jwtOptions);

Alternatively, we can use them Get() to avoid using the “new” keyword.

JwtOptions jwtOptions = Configuration.GetSection("Jwt").Get<JwtOptions>();        services.AddSingleton(mailFeature);

To use the instance in our logic, we can just inject the class into the constructor of the component where it will be used.

public class HomeController : ControllerBase
{
    private readonly JwtOptions jwtOptions;

    public JwtController(JwtOptions jwtOptions)
    {
        this.jwtOptions = jwtOptions;
    }

Although this approach works, the drawback is also obvious that we still have to explicitly create an instance by ourselves while using the dependency injection.

Here is where the IOptions pattern comes into play.

How to Use IOptions Pattern

The above logic can be written as:

Instead of using Bind or Get methods, we can achieve this by using GetSection to get a configuration sub-section with the specified key.

In this way, we can easily achieve the same result by writing easier and less code.

The IOptions interface is part of the Microsoft.Extensions.Options namespace, which is available implicitly in the .NET Core package.

To get the TOptions instance in our controller or services, there are three interfaces provided by this package.

  • IOptions
  • IOptionsSnapshot
  • IOptionsMonitor

They can be used in the same way but for different scenarios, like:

When to Use Which

IOptions:

  • registered as a singleton service, hence can be injected into any service
  • configuration changes cannot be re-read once instantiated, since it’s a singleton
  • Doesn’t support “named” options

IOptionsSnapshot:

  • registered a scoped service, hence cannot be used inside the singleton service
  • enable reload when configuration changed
  • Supports “named” options

IOptionsMonitor:

  • registered as a singleton service, hence can be injected into any service
  • enable reload when configuration changed
  • Supports “named” options

Check here for understanding what is named option.

Web Development
Back End Development
Csharp
Dotnet
Recommended from ReadMedium