0

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 Foos 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);
    });
}
StackOverthrow
  • 1,158
  • 11
  • 23
  • How you expect to consume different instances of the same type `Foo`? How consumer class can "specify" that it needs instance of `Foo` with config from section "one" and not fro. section "two"? – Fabio Jan 05 '21 at 21:21
  • @Fabio The consumer requires an `IEnumerable`. – StackOverthrow Jan 05 '21 at 21:24
  • Can't you make those classes implement some common interface and then find all the classes that implement it? Something like [this](https://www.solvingsoftware.dev/calling-a-method-on-all-classes-that-implement-a-particular-interface-in-c/) – nunohpinheiro Feb 03 '21 at 22:55
  • @NPinheiro Do you mean have `Foo` implement `IFoo` and consume an `IEnumerable`? Or give `Foo` some kind of "set config" method, then consume an `IEnumerable` and `IEnumerable` and match them up? I don't see how either helps me. – StackOverthrow Feb 04 '21 at 01:32
  • 1
    Well, yes, my idea was sort like that... You could find all the classes that implemented `IFoo`, all of them having their configuration setting method and properties. Then, you would just go through the classes and add as singletons. But maybe I did not fully understand your use case. If you may, please provide some more information on how that several "Foo's" would be, how you wanted to configure them and how you use those input services in the constructor – nunohpinheiro Feb 04 '21 at 12:44

0 Answers0