Pranasas Pranasas - 16 days ago 6
C# Question

Should I combine interface implementations using reflection (C#)?

I'll present a simplified case of my situation.

So, I'm making some transformations within

MyClass
type

public interface ITransformer
{
List<MyClass> Transform(MyClass item);
}


Because the transformations are really different, it makes perfect sense to provide them as different implementations of
ITransformer
.

However, now there is a need to have a combined result of all possible transformations. Something like
GlobalTransformer : ITransformer
whose
Transform
method calls all other implementations and combines their results...

Does it make sense? Should I use reflection for it? Or should I approach the problem differently somehow?

Answer

I would go that way:

public class GlobalTransformer : ITransformer
{
     private readonly IList<ITransformer> _availableTransformers;

     public GlobalTransformer(IList<ITransformer> availableTransformers)
     {
         _availableTransformers = _availableTransformers;
     }

     public List<MyClass> override Transform(MyClass item) {
        List<MyClass> result = new List<MyClass>();
        foreach (var item in _availableTransformers) {
           result.AddRange(item.Transform(item));
        }
        return result;
     }
}

I would then go one step forward and use IoC like Autofac or SimpleInjector to inject that list to your GlobalTransformer class

I also would strongly avoid reflection as it's slow.