1

I have a library that configures dependency injection for another library (via IServiceCollection extension). However, that other library requires a different implementation of a service that is already registered in the application that will be using it even though only one implementation of that service is expected in the application.

I.e., Application relies on Service A with implementation A1 and Service B (from a separate library) that relies on Service A with implementation A2. Both implementations A1 and A2 come from libraries and are internal (registered using library-specific IServiceCollection extensions).

What is the way to make this work without exposing internal classes or changing the service implementation used by the application?

KirEvse
  • 305
  • 3
  • 15
  • If you have multiple implementation of Interface the you can get the whole list and then you can put the condition. Similar [question](https://stackoverflow.com/questions/39174989/how-to-register-multiple-implementations-of-the-same-interface-in-asp-net-core) on SO. One more [link](https://thecodeblogger.com/2022/09/16/net-dependency-injection-one-interface-and-multiple-implementations/) – शेखर Jan 07 '23 at 03:19
  • Unfortunately, @शेखर, this will not help as dependent components all expect a single reference. – KirEvse Jan 19 '23 at 15:12

1 Answers1

2

Register the service in the library that you have access to as a concrete type.

So that the services are registered like this:

services.AddTransient<ServiceA>();
services.AddTransient<IService, ServiceB>();

Then just refer to them like this:

public class ClassThatNeedsServiceA
{
    private ServiceA _serviceA;
    
    public ClassThatNeedsServiceA(ServiceA serviceA)
    {
        _serviceA = serviceA;
    }
}

public class ClassThatNeedsServiceB
{
    private ServiceB _serviceB;
    
    public ClassThatNeedsServiceA(IService serviceB)
    {
        _serviceB = serviceB;
    }
}

This will allow both services to be accessed correctly where needed.

If the new library needs to expose access to ServiceA and or ServiceB externally then it might be an indication that they should not be internal.

YungDeiza
  • 3,128
  • 1
  • 7
  • 32
  • 1
    I ended up creating a component holder component that allowed to choose implementation upon DI setup. – KirEvse Jan 19 '23 at 15:15