mardi 13 avril 2021

Get all classes that implement an interface and call a function in .NET Core

How can I get all classes that implements a specific interface then call a function of that class if a string member of the specific class matches a given one?

Basically what I have is a ICommandHandler interface:

interface ICommandHandler
{
    string Command { get; }
    Task ExecuteAsync();
}

and a class that implements it:

public class StartCommand : ICommandHandler
{

    public string Command { get => "start"; }
    public async Task ExecuteAsync()
    {
      // do something
    }
}

What I want to do is to get all the classes that implements the ICommandHandler interface, then verify if the class.Command equals a specific string and if it does then call the ExecuteAsync method.

I've tried using this answer here: https://stackoverflow.com/a/45382386/15306888 but the class.Command is always null





Aucun commentaire:

Enregistrer un commentaire