jeudi 23 avril 2020

How to inject all classes implementing the same generic interface in the constructor using StructureMap?

I have a bunch of data fetchers which all has the almost same signature. The only thing that differs is the return type. The return type is specified as T:

I have this interface:

public interface IDataFetcher<T>
{
    T FetchData(MyObject data);
}

Next I have a about 10 implementations of this interface. In de the calling code I want to do something like this:

public class FetchCommandHandler
{
    private readonly IEnumerable<IDataFetcher<T>> _fetchers;

    public FetchCommandHandler(IEnumerable<IDataFetcher<T>> fetchers) // this of course does not work
    {
        _fetchers = fetchers;
    }

    public MyResult Handle()
    {
        var myObj = new MyObject(); // get object from database

        foreach(var fetcher in _fetchers)
        {
           var result = fetcher.FetchData(myObj);
           // do something with result
        }
    }
}

So, in the end, what I want is not have to inject each DataFetcher<T> implementation in the constructor. I am looking for a way to retreive all the registrations of IDataFetcher<T> from StructureMap.

I am open for every other design that achieves the same result, ie, not inject each implementation in the constructor.

Aucun commentaire:

Enregistrer un commentaire