This question seems closely related to the idea of named dependencies, which I know aren't supported. But I can't help feeling I'm missing something.
I'm ultimately trying to consume an IEnumerable<Foo>
. This is easily done by adding multiple instances to the service collection. But can I add multiple Foo
s that differ in their configuration, while still taking advantage of DI magic to provide their other dependencies? I'm trying to avoid writing an extension method like this, which would require maintenance any time Foo
's dependencies change:
public static void AddFoo(this IServiceCollection services, string configSection)
{
services.AddSingleton(sp =>
{
var bar = sp.GetRequiredService<Bar>();
var baz = sp.GetRequiredService<Baz>();
var qux = sp.GetRequiredService<Qux>();
var config = sp.GetRequiredService<IConfiguration>().GetSection(configSection).Get<FooConfig>();
return new Foo(bar, baz, qux, config);
});
}