vendredi 13 mars 2020

Is there a way to use reflection to instantiate instances of a class that either implement a given interface or inherit from a given base class

Given I have the following 2 classes (there are actually many more that follow the pattern below - potentially dozens as I keep adding):

public class FooCollector: BaseCollector, ICollector<Foo>
{
    public FooCollector(Dep1 dep1, Dep2 dep2, Dep3 dep3) : base(dep1, dep2, dep3)
    {
    }

    public async Task<List<Foo>> GetItems()
    {
       //Implementation for getting foos
    }
}

public class BarCollector: BaseCollector, ICollector<Bar>
{
    public BarCollector(Dep1 dep1, Dep2 dep2, Dep3 dep3) : base(dep1, dep2, dep3)
    {
    }

    public async Task<List<Bar>> GetItems()
    {
       //Implementation for getting bars
    }
}

Base class:

public abstract class BaseCollector
{
    protected readonly Dep1 Dep1;
    protected readonly Dep2 Dep2;
    protected readonly Dep3 Dep3;

    protected BaseCollector(Dep1 dep1, Dep2 dep2, Dep3 dep3)
    {
        Dep1 = dep1;
        Dep2 = dep2;
        Dep3 = dep3;
    }

    protected void BaseMethod1()
    {
        //BaseMethod1 implementation
    }

    protected DateTime BaseMethod2()
    {
        //BaseMethod2 implementation
    }
}

and interface:

public interface ICollector<T> where T : class
{
    Task<List<T>> GetItems();
}

How would I go about using reflection to instantiate an instance of every derived class and invoke its GetItems method? Implementing a generic interface and not having a parameterless constructor have stymied my efforts at trying to figure out other implementations. Is what I'm doing here possible or perhaps theres a better way to solve the issue at hand?





Aucun commentaire:

Enregistrer un commentaire