Skip to content

Allow controlling options lifetime from the composition root #3

@Carl-Hugo

Description

@Carl-Hugo

Create .Net plain options injection helpers that support the following:

  • AddTransientOptions<TOptions>()
  • AddScopedOptions<TOptions>()
  • AddSingletonOptions<TOptions>()

Conditional options injection should be supported.

Implementation example:

public static class OptionsBuilderExtensions
{
    public static OptionsBuilder<TOptions> AddScopedOptions<TOptions>(this IServiceCollection services)
            where TOptions : class
    {
        services.AddScoped(serviceProvider => serviceProvider
            .GetService<IOptionsSnapshot<TOptions>>().Value);
        return services.AddOptions<TOptions>();
    }
}

Registration example:

services.AddScopedOptions<Options>()
    .Configure(o => o.MyImportantProperty = "Some important value");

That should allow injection the options directly, controlling the lifetime from the composition root instead of from the consumer, like the following:

public class Consumer
{
    private readonly Options _options;
    public Consumer(Options options)
    {
        _options = options ?? throw new ArgumentNullException(nameof(options));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions