Search code examples
c#design-patterns

What is the right design pattern for executing code per number of classes?


I am writing a console app to migrate data from one system to another. I have an interface and implementation for each entity type. I would like the app to execute code in each implementation, so if at the start I have 10 interfaces/implementations the 10 types are executed/migrated. The design should support adding more types and the execution should just scan or know another was added...so forth and so on.

I understand this is a loaded question, but I am on my way. It is a .NET 6 console app. I am using Microsoft DI Container. I just dont want to physically call code in each implemented class.

I've been writing code for some time, but learning DI now (unfortunately late to the game, but nonetheless here now). Thanks for the tips!


Solution

  • The typical pattern here is:

    • have all the types share an interface
    • use reflection to enumerate the types in your assembly that implement the interface
    • create an instance of each type and cast it to the interface type
    • execute the code,
    foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (type.GetInterfaces().Contains(typeof(ICanDoTheThing)))
        {
            var foo = Activator.CreateInstance(type) as ICanDoTheThing;
            foo.DoTheThing();
        }
    }
    

    You can use some other heuristic to determine the target types, like a naming convention or a custom attribute, but a shared interface is the most convenient since it both identifies the target types and gives you an entry point to run the code.