vendredi 5 avril 2019

c# safest way check whether a type contains a type in its interfaces

what is the safest way to compare two types at runtime ?

public interface IHandler<T> where T : Command {

}

public class CleanupHandler : IHandler<CleanupCommand> {
}

var Handlers = GetServices(typeof(IHandler<>));


static IEnumerable<object> GetServices(Type serviceType) {
            var services= _services.Where(r => r.implementationType.GetInterfaces().Contains(serviceType)) /* issue here */
                                   .Select(r => r.implementation);

            return services;
 }

_services is an Enumerable of

public class Metadata {
    public Type serviceType { get; protected set; }
    public Type implementationType { get; protected set; }
    public object implementation { get; protected set; }
}

if we change the check from :

r.implementationType.GetInterfaces().Contains(serviceType)

to

r.implementationType.GetInterfaces().Count(x => x.Name == serviceType.Name) > 0

it works but thats not safe at all , the type is indeed the same but it doesnt work.

can i have a hint?





Aucun commentaire:

Enregistrer un commentaire