netchicken
netchicken

Reputation: 485

How do I inject a multiple interface service into a class?

Following this example I can create a service with multiple interfaces

builder.Services.AddSingleton<SweetAlert>();
builder.Services.AddSingleton<ISweetAlert, SweetAlert>(implementationFactory: x => 
x.GetRequiredService<SweetAlert>());
builder.Services.AddSingleton<ISweetAlert2, SweetAlert>(x => 
x.GetRequiredService<SweetAlert>());
builder.Services.AddAutoMapper(typeof(Program));

But then how do I inject it into the class? Either I don't get it or the author doesn't address the situation.

Because it has two interfaces the usual constructor injection won't work.

Upvotes: 0

Views: 539

Answers (1)

quetzalcoatl
quetzalcoatl

Reputation: 33526

Assuming no other problems in the code, injecting two (or more) dependencies to a component should be as simple as adding multiple parameters to its constructor

public class Foobarizer
{
    private readonly ISweetAlert alert1;
    private readonly ISweetAlert2 alert2;

    public Foobarizer(
        ISweetAlert alert1,
        ISweetAlert2 alert2
    )
    {
        this.alert1 = alert1;
        this.alert2 = alert2;
    }

    public void DoTheTrick()
    {
        this.alert1.Foo();
        this.alert2.Bar();
    }
}

For this, it doesn't matter where the instances of ISweetAlert and ISweetAlert2 come from. For this Foobarizer with 2 dependencies, they could be separate objects, they could be the same object, no difference. At least from Foobarizer's point of view.

For the container, there is a small difference, and that's why the article you cited provided a section on this special case of sharing a single singleton under two interfaces. But it doesn't impact (or: shouldn't impact but sometimes does (*)) how the Foobarizer looks like.

(*) that somewhat depends on the DI/IoCC library, but you probably use aspnet6's built-in one, so, it doesn't.

Upvotes: 2

Related Questions