Skip to content

03. Registering Options

Tim Maes edited this page Oct 15, 2024 · 1 revision

Bindicate simplifies the registration and configuration of options classes using IOptions<T>.

Defining Options classes

Decorate your options class with [RegisterOptions] and specify the configuration section.

[RegisterOptions("MyOptions")]
public class MyOptions
{
    public string Setting { get; set; }
}

Configuring Options

Ensure the corresponding section exists in your appsettings.json

{
  "MyOptions": {
    "Setting": "Value"
  }
}

Registering Options

When registering services, include the WithOptions method and pass the configuration.

builder.Services
    .AddAutowiringForAssembly(Assembly.GetExecutingAssembly())
    .WithOptions(configuration)
    .Register();

Using Options in Services

Inject IOptions<T> into your services.

public class MyService
{
    private readonly MyOptions _options;

    public MyService(IOptions<MyOptions> options)
    {
        _options = options.Value;
    }

    // Use _options.Setting as needed
}

Clone this wiki locally