vendredi 26 octobre 2018

Loop through Interfaces of an object

I'm creating a generic Service Locator, but have a problem. I have a method to add or replace a service. The service has to be replaced if there is only 1 candidate in the current service list.

// IA  - TestA
// IB  - TestB
// IA/IB - TestAB
// <IB> TestAB 
public static void AddOrReplaceService<T>(T serviceToAdd) where T:  class
{
    if (serviceToAdd == null)
        throw new ArgumentNullException(nameof(serviceToAdd));
    List<T> foundServices = new List<T>();
    int index = -1;
    for (int i = 0; i < _services.Count; i++)
    {
        if (!(_services[i] is T) 
            && !_services[i].GetType().IsAssignableFrom(typeof(T))
            && !_services[i].GetType().IsInstanceOfType(serviceToAdd)
            && !serviceToAdd.GetType().IsInstanceOfType(_services[i]))
            continue;
        foundServices.Add((T) _services[i]);
        if (index == -1)
            index = i;
    }
    switch (foundServices.Count)
    {
        case 0:
            AddService(serviceToAdd);
            break;
        case 1:
            _services[index] = serviceToAdd;
            return;
        default:
            throw new MultipleServicesAlreadyExistsException("Multiple services found with " + typeof(T).Name
                                                + foundServices.ToStringCollection(", "));
    }
}

To test my Service Locator I have 2 interfaces IA and IB and 3 classes, TestA : IA, TestB : IB and TestAB : IA, IB

The thing is if both TestA and TestB are in the list and you try to add TestAB it should give an exception because both TestA and TestB are implementing interfaces of TestAB.

I tried to add a bunch of AssignableFrom etc. logic. However, I can't get it to work.

Help would be much appreciated! Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire