Skip to content

Instantly share code, notes, and snippets.

@ericsampson
Last active November 15, 2020 19:22
Show Gist options
  • Save ericsampson/bb37bd6da0748af2e928ee750563452a to your computer and use it in GitHub Desktop.
Save ericsampson/bb37bd6da0748af2e928ee750563452a to your computer and use it in GitHub Desktop.
Configuration pattern and ConfigureServices
// I have a service that needs to be initialized with a FooOptions and then added to the DI container.
// I also want to have IOptions<FooOptions> in the DI container to allow injection in other methods.
// How should I write my AddFoo extension method to support this?
public void ConfigureServices(IServiceCollection services)
{
services.AddFoo(fooOptions =>
{
configuration.GetSection("FooOptions").Bind(fooOptions)
fooOptions.param = "override";
});
}
namespace Microsoft.Extensions.DependencyInjection
{
public static class MyFooExtensions
{
public static IServiceCollection AddFoo(this IServiceCollection services,
Action<FooOptions> setupOptions)
{
services.Configure<FooOptions>(setupOptions);
services.AddSingleton<IFoo>(sp =>
{
var options = sp.GetRequiredService<IOptions<FooOptions>>();
return new FooFactory(options.Value);
};
return services;
}
}
}
@ericsampson
Copy link
Author

Thanks again @andrewlock, I'll give this all a go. Really appreciate the help :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment