michasaucer
michasaucer

Reputation: 5228

How to find Implementation of Service by type?

I have two services in my application:

ServiceA : IService
ServiceB : IService

I want to pass Type info of service that i need to (ServiceA or ServiceB) to second class.

Then, i want to grab that service in that second class.

IEnumerable<IService> services // i get it from DI by constructor, length = 2
                               // becuase i have two implementations of it
services.FirstOrDefault(x => ... and how to grab for example ServiceA?)

So what i should pass to my second class to get the implementation of IService of asked Type? That services exist in same assembly and i pass list of this services by .NET Core DI Container.

Services and all classes exist in same project but in diffrent namespaces (but they have reference)

EDIT:

Sorry for not clarify this, i need to pass info about object by string becuase im sending JSON to it. So i need grab some kind of info about Service as string, then deserialize it in second class and based on string find proper service from services list

EDIT2:

Example, what i want to do:

// logic, i know i need ServiceA, pseudocode:

return ServiceB.GetType().ToString();

// then, serialize it to json:

string json = object.Serialize(); // object where i have property for example : "service": "ServiceB"

// second class

public Task Handler(Object input)
{
   // deserialize input;
   // and grab service
   var service = services.FirstOrDefault(x => x .....);
}

Upvotes: 1

Views: 1474

Answers (1)

Matt
Matt

Reputation: 27001

You need to get the type of the object, which is done by x.GetType() and compare it against the ServiceA type (typeof(ServiceA)).

LinqPad example (just copy+paste into LinqPad):

void Main()
{
    IEnumerable<IService> services = new List<IService>() { new ServiceA(),
                                                            new ServiceB() };
    var service = services.FirstOrDefault(x => x.GetType()==typeof(ServiceA));
    service.Dump();
}


class ServiceA : IService { }
class ServiceB : IService { }
interface IService { }

Run it in .NET Fiddle

Alternatively, you can also use service.GetType().Name to get the type name as string, and then match the string, i.e.

string strService = "ServiceA";
var service = services.FirstOrDefault(x => GetType().Name==strService);

If you have different namespaces, you might need to add using statements, or do a fully-qualified reference of ServiceA.

Upvotes: 2

Related Questions