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?

2
  • If you have multiple implementation of Interface the you can get the whole list and then you can put the condition. Similar question on SO. One more link Commented Jan 7, 2023 at 3:19
  • Unfortunately, @शेखर, this will not help as dependent components all expect a single reference. Commented Jan 19, 2023 at 15:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up creating a component holder component that allowed to choose implementation upon DI setup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.