Options pattern in ASP.NET Core

The options pattern uses classes to provide strongly typed access to groups of related settings.

Setup

  1. Install the following libraries
1
2
3
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
  1. Create your appsettings.json file - there can be nesting like Services:FooService
1
2
3
4
5
6
7
8
9
10
{
"RedisServer": {
"ConnectionString": "localhost:6379,allowAdmin=true"
},
"Services": {
"FooService": {
"Url": "http://localhost:5000"
}
}
}
  1. Create the options class file, example RedisServerOptions.
1
2
3
4
5
6
7
8
9
namespace RedisAdmin.Infrastructure.IntegrationTests.Common
{
public class RedisServerOptions
{
public const string RedisServer = "RedisServer";

public string ConnectionString { get; set; }
}
}

For the nested Services:FooService example the const string would be

1
2
3
4
5
6
7
8
9
namespace RedisAdmin.Infrastructure.IntegrationTests.Common
{
public class FooServiceOptions
{
public const string FooService = "Services:FooService";

public string Url { get; set; }
}
}
  1. Populate the file using ConfigurationBuilder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CollectionFixture
{
private readonly RedisServerOptions _redisServerOptions;

public CollectionFixture()
{
var appSettings = "appsettings.json";

var configuration = new ConfigurationBuilder()
.AddJsonFile(appSettings)
.Build();

_redisServerOptions = configuration
.GetSection(RedisServerOptions.RedisServer)
.Get<RedisServerOptions>();
}

The example above is manual for integration tests. You can use your applications start up instead and pop the options file into the dependency injection container.

1
2
services
.Configure<RedisServerOptions>(configuration.GetSection(RedisServerOptions.RedisServer));

This can then be injected into your applications constructor as follows

1
2
3
4
5
6
7
8
public class FooServiceClient : IFooServiceClient
{
private readonly FooServiceOptions _options;

public FooServiceClient(IOptions<FooServiceOptions> options)
{
_options = options.Value;
}

References