EnenDaveyBoy
EnenDaveyBoy

Reputation: 251

Dependency Injection - interfaces in a Dictionary c#

I want to inject a IDictionary of {key, interface} into a contructor, but I have no idea how to set it up in the program.cs

I can initiate the Interfaces and I can could initiate an IDictionary but I have no idea how to combine them.

Any suggestions would be appriciated.

Additional Context:

So i need to inject my services like

I need to inject the services eg,

s.AddTransient<IFooService, AFooService>();
s.AddTransient<IFooService, BFooService>();

but in the contructor I want

public MyClass(IDictionary<string, IFooService> fooServices)

Upvotes: 1

Views: 2115

Answers (2)

snipsnipsnip
snipsnipsnip

Reputation: 2575

A bit intrusive alternative is to add a key property to IFooService. Then you can have MEDI enumerate services:

interface IFooService
{
    string FooKey { get; }
    // ... void Work(); ...
}

class MyClass
{
    private IDictionary<string, IFooService> fooServices;

    public MyClass(IEnumerable<IFooService> fooServices) 
    {
        this.fooServices = fooServices.ToDictionary(foo => foo.FooKey);
    }
}

class Startup
{
    public void Configure(IServiceCollection s) 
    {
        // you can keep the initialization as-is. DI will populate IEnumerable
        s.AddTransient<IFooService, AFooService>();
        s.AddTransient<IFooService, BFooService>();
    }
}

I like this approach because my app performs DI registration via reflection, so adding another IFooService is as simple as adding a new class file.

Upvotes: 1

Steven
Steven

Reputation: 172606

services.AddTransient<MyClass>();
services.AddTransient<AFooService>();
services.AddTransient<BFooService>();

services.AddTransient<IDictionary<string, IFooService>>(sp =>
    new Dictionary<string, IFooService>
    {
        { "A", sp.GetRequiredService<AFooService>() },
        { "B", sp.GetRequiredService<BFooService>() },
    });
``

Upvotes: 5

Related Questions