Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Last active September 12, 2018 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/9ffe48f732b9842805564347c4b2e99d to your computer and use it in GitHub Desktop.
Save yetanotherchris/9ffe48f732b9842805564347c4b2e99d to your computer and use it in GitHub Desktop.
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