我有两个示例类
class ClassToResolve
{
private List<CollectionItem> _coll;
public ClassToResolve(List<CollectionItem> coll)
{
_coll = coll;
}
}
class CollectionItem
{
//...
}
Run Code Online (Sandbox Code Playgroud)
我需要解决ClassToResolve
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
new CollectionItem(),
new CollectionItem(),
new CollectionItem()
}
);
Run Code Online (Sandbox Code Playgroud)
现在我以某种方式解决它
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>()
}
);
Run Code Online (Sandbox Code Playgroud)
有没有办法使用动态注册解析ClassToResolve?
.net c# dependency-injection inversion-of-control unity-container
是否可以在Unity或其他类型的IoC库中注入这样的依赖项列表?
public class Crawler
{
public Crawler(IEnumerable<IParser> parsers)
{
// init here...
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我可以在我的容器中注册多个IParser,然后解决它们.
可能吗?谢谢
给出以下界面:
public interface IMyProcessor
{
void Process();
}
Run Code Online (Sandbox Code Playgroud)
我希望能够注册多个实现并让我的DI容器将其中的可枚举注入到这样的类中:
public class MyProcessorLibrary
{
private readonly IMyProcessor[] _processors;
public MyProcessingThing(IMyProcessor[] processors)
{
this._processors = processors;
}
public void ProcessAll()
{
foreach (var processor in this._processors)
{
processor.Process();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?我当前MyProcessorLibrary的IMyProcessor实现静态查找所有实现,但如果可以的话,我宁愿通过容器来实现.我正在使用Unity,但我很好奇其他容器是否支持它.
编辑:
谢谢你到目前为止的答案; 要清楚我想注入MyProcessorLibrary另一个类,并将其构建为依赖对象树的连接的一部分,例如
public class MyProcessorRepository
{
public MyProcessorRepository(MyProcessorLibrary processorLibrary)
{
}
}
public class MyProcessorService
{
public MyProcessorService(MyProcessorRepository processorRepository)
{
}
}
var container = new UnityContainer();
// Register a bunch of IMyProcessors... …Run Code Online (Sandbox Code Playgroud)