Instantly share code, notes, and snippets.

Embed
What would you like to do?
IOptions extension method to bind both IOptions<T> and T as a singleton
public static class OptionsExtensions
{
public static IServiceCollection ConfigureOptionsAndInstance<T>(this IServiceCollection services, IConfigurationSection section)
where T : class, IOptions<T>, new()
{
services.Configure<T>(section);
services.AddSingleton<T>(provider => provider.GetService<IOptions<T>>().Value);
return services;
}
}
public class S3Configuration : IOptions<S3Configuration>
{
public string SecretKey { get; set; }
[JsonIgnore]
public S3Configuration Value => this;
}
// Example DI configuration
public class DependencyInjection
{
public static void ConfigureServices(IServiceCollection services, IConfigurationRoot configurationRoot)
{
services.AddOptions();
services.ConfigureOptionsAndInstance<S3Configuration>(configurationRoot.GetSection("S3"));
}
}
// Example test case
[Fact]
public void Test1()
{
// given
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(new Dictionary<string, string>
{
{ "S3:SecretKey", "123" }
});
var serviceCollection = new ServiceCollection();
var configurationRoot = configurationBuilder.Build();
// when
DependencyInjection.ConfigureServices(serviceCollection, configurationRoot);
// then
ServiceProvider provider = services.BuildServiceProvider();
var s3Options = provider.GetService<IOptions<S3Configuration>>();
var s3Config = provider.GetService<S3Configuration>();
s3Options.ShouldNotBeNull();
s3Options.Value.ShouldNotBeNull();
s3Options.Value.SecretKey.ShouldBe("123");
s3Options.Value.AccessKey.ShouldBe("999");
s3Options.Value.Region.ShouldBe("eu-west-1");
s3Config.ShouldNotBeNull();
s3Config.SecretKey.ShouldBe("123");
s3Config.AccessKey.ShouldBe("999");
s3Config.Region.ShouldBe("eu-west-1");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment