[英]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:
返回类型指定为 T:
I have this interface:我有这个界面:
public interface IDataFetcher<T>
{
T FetchData(MyObject data);
}
Next I have a about 10 implementations of this interface.接下来我有大约 10 个这个接口的实现。 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.所以,最后,我想要的是不必在构造函数中注入每个
DataFetcher<T>
实现。 I am looking for a way to retreive all the registrations of IDataFetcher<T>
from StructureMap.我正在寻找一种方法来从 StructureMap 中检索
IDataFetcher<T>
的所有注册。
I am open for every other design that achieves the same result, ie, not inject each implementation in the constructor.我对实现相同结果的所有其他设计持开放态度,即不在构造函数中注入每个实现。
What we can do is introduce another interface for return type and all the types that will be returned will implement it.我们可以做的是为返回类型引入另一个接口,所有将要返回的类型都将实现它。
Define an interface:定义一个接口:
public interface IData
{
}
public interface IDataFetcher<T> where T : IData
{
T FetchData(MyObject data);
}
As an example a type that would be returned:作为示例,将返回一个类型:
public class FooData : IData
{
}
and it's DataFetcher implementation will look like:它的 DataFetcher 实现看起来像:
public class FooDataFetcher : IDataFetcher<FooData>
{
public FooData FetchData(MyObject data)
{
// logic here and return instance of FooData
}
}
Now what we can do is define the Handler class something like:现在我们可以做的是定义 Handler class 像这样:
public class FetchCommandHandler
{
private readonly IEnumerable<IDataFetcher<IData>> _fetchers;
public FetchCommandHandler(IEnumerable<IDataFetcher<IData>> 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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.