0
votes

I have an interface that has 2 implementation IMYService MyServiceA MYServiceB

Here the Implementation is dependent on some data in the request header used by the construtor of the Services like If Header has value of internalId then use MyServiceA and pass that Id to the services in constructor while if the value is missing use MyServiceB where as this service construct does not expect id.

My Controller is defined with DI for IMyservice

1

1 Answers

0
votes

In general, you need a factory. That's generally a separate class that is responsible to managing instances of a particular similar type of thing and returns the appropriate instance based on some sort of convention or condition. For example, if you've used IHttpClientFactory, you've see one in action.

Since the implementation depends on the request, you can cheat a little by using the "factory" overload of AddScoped:

services.AddScoped<IMyService>(p => 
{
    // return either MyServiceA or MyServiceB
});

The p param of the lambda is actually a scoped instance of IServiceProvider, so you can do stuff like pull out IHttpContextAccessor to look at the request details.