lundi 16 décembre 2019

How to dynamically invoke a class based on a string?

Can you give me some guidance to dynamically load class based on name. The name is provided as a argument at runtime.

    static void Main(string[] args) 
    {
        ...
    } 

Let's say my argument is "parrot" then I would like to load my parrotProcessor class. If my argument name is "snake" then I load my To make snakeProcessor. Of course this mean I have a parrot and snake processor class that inherit an interface IProcessor. I don't know what could be the list of all processor. this list is maintained by other developers and they can create what they want.

Example of my processor interface:

    public interface IProcessor
    {
        void Process();
    }

And in my Program.cs

    static void Main(string[] args) 
    {
        var processor = GetProcessor(args[0]);
        processor.Process();
    } 

My question is what should I do in GetProcessor() method?

Here is what I have at this moment:

    private IProcessor GetProcessor(string name)
    {
        switch (name)
        {
             case "ant":
                return new AntProcessor();
             case "parrot":
                return new ParrotProcessor();
             case "snake":
                return new SnakeProcessor();
             default:
                throw new ArgumentException("Case not found");
        }
    }

But this mean I must updated this ugly switch each time I create a new processor specialized class. This is not possible. I can do it now for development but not for long term.

What are the solutions? Should I use something similar to DI with NInject or am I mixing everything? Can I simply use the Invoke method? And why Invoke or DI? I know this question is kind of open question but it is something that happen often in code of many people so I suppose there is unique best practice about it.





Aucun commentaire:

Enregistrer un commentaire