2

I want to use dependency injection for a class that takes an interface IService in its constructor. But I have several implementations of this interface. Both implementations are needed by other classes as well so I cannot simply only initiate the one needed. I'm using Microsoft.Extensions.DependencyInjection

Here's an example that tries to show my classes

public interface IService { }

public class ServiceA : IService { ... }

public class ServiceB : IService { ... }

public class Foo
{
    public Foo(IService service) { }
}

public class Bar
{
    public Bar(IService service)  { }
}

If I did not have several implementations I'd inject it like following:

builder.Services.AddSingleton<IService, ServiceA>();
builder.Services.AddSingleton<Foo>();

In the example I'd need Foo to be initialized with ServiceA and Bar to be initialized with ServiceB.

Steven
  • 166,672
  • 24
  • 332
  • 435
jkc
  • 31
  • 1
  • 1
    You will have to segregate your iterfaces further, so your hierachy will be as follows: `ServiceA->IServiceA->IService`. Then when registering you'll bind your Service to IServiceA instead of IService – Alex Jul 23 '19 at 06:48

1 Answers1

1

Something like this (typing directly into the browser):

builder.Services.AddSingleton<ServiceA>();
builder.Services.AddSingleton<ServiceB>();
builder.Services.AddSingleton<Foo>(c =>
    ActivatorUtilities.CreateInstance<Foo>(c, c.GetRequiredService<ServiceA>())); 
builder.Services.AddSingleton<Bar>(c =>
    ActivatorUtilities.CreateInstance<Bar>(c, c.GetRequiredService<ServiceB>())); 
Steven
  • 166,672
  • 24
  • 332
  • 435
qujck
  • 14,388
  • 4
  • 45
  • 74