Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow controlling options lifetime from the composition root #3

Open
Carl-Hugo opened this issue Apr 23, 2020 · 0 comments
Open

Allow controlling options lifetime from the composition root #3

Carl-Hugo opened this issue Apr 23, 2020 · 0 comments

Comments

@Carl-Hugo
Copy link
Member

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));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant