How to find all classes of a specific interface in an assembly in .net

I have a scenario according to which I want n the number of classes to look at the same data and decide whether to do any work. Work is performed by a team, and several teams can work with data at the same time. I was thinking of creating a class for each command that will implement the CreateWork interface. All CreateWork classes must have an opinion. At the moment there are not many, but in the future there will be many more.

Sudo code for my planned solution

For each CreateWork class in assembly
    class.CheckAndCreateWork(dataIn,returnedCollectionOfWorkToBeDone)
Next

Is there a design template that can do this in an elegant way? It seems a bit messy to surround every assembly class.

Greetings

+3
3

:

( ):

foreach(var type in Assembly.GetExecutingAssembly().GetTypes()) {
    if(typeof(ITheInterface).IsAssignableFrom(type)) {
        var theInstance=(ITheInterface)Activator.CreateInstance(type);
        //do something with theInstance
    }
}
+9

, .

+1

. . assemlby, , , - assemlby.GetExportedTypes() Activator.CreateInstance() ( , ), )

:

var workerTypes = assembly.GetExportedTypes()
    .Where(t => t.IsClass && !t.IsAbstract && typeof(IWorker).IsAssignableFrom(t));

foreach (var type in workerTypes)
{
    var worker = (IWorker)Activator.CreateInstance(type);
    worker.CheckAndCreateWork("Work");
}

assemlby - . Assemlby.LoadFrom() - :

var assembly = typeof(SomeClassInTargetAssembly).Assembly;

*. DLL (, ./plugins), :

foreach (var file in Directory.GetFiles(PluginsFolder, "*.dll"))
{
    var assembly = Assembly.LoadFrom(file);
    var workerTypes = GetWorkerTypes(assembly);
    RunWorkers(workerTypes);
}

You may want to separate the processes of loading and starting workers to avoid loading work types several times (in case you need to run employees more than once during the life of the application)

0
source

Source: https://habr.com/ru/post/1723753/


All Articles