团结.NET:依赖列表 [英] Unity .NET: List of dependencies

查看:154
本文介绍了团结.NET:依赖列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能为在注入依赖这样的列表的统一或其他类型的IoC库?

Is it possible to inject a list of dependencies like this in Unity or other kind of IoC libraries?

public class Crawler 
{
    public Crawler(IEnumerable<IParser> parsers) 
    {
         // init here...
    }
}

在这样我可以在我的容器中,然后注册多个IParser解决这些问题。

In this way I can register multiple IParser in my container and then resolve them.

这可能吗?谢谢

推荐答案

这是可能的,但你需要应用一些解决方法。首先,你需要在每个 IParser 与在Unity容器的名称注册。其次,你需要从注册测绘 IParser [] 的IEnumerable< IParser> 在容器中。否则,容器不能注入的解析器构造。 。Here's我是如何做之前

It is possible but you need to apply some workarounds. First you need to register each IParser with a name in the Unity Container. Second you need to register a mapping from IParser[] to IEnumerable<IParser> in the container. Otherwise the container cannot inject the parsers to the constructor. Here´s how i have done it before.

IUnityContainer container = new UnityContainer();

container.RegisterType<IParser, SuperParser>("SuperParser");
container.RegisterType<IParser, DefaultParser>("DefaultParser");
container.RegisterType<IParser, BasicParser>("BasicParser");
container.RegisterType<IEnumerable<IParser>, IParser[]>();
container.RegisterType<Crawler>();

Crawler crawler = container.Resolve<Crawler>();



我已经放弃通过引入一个工厂,它封装统一建设所需的类型此解决方案。 。Here's我怎么会做它在你的情况

I have discarded this solution by introducing a factory, that encapsulates unity to construct the needed types. Here´s how i would do it in your case.

public interface IParserFactory{
  IEnumerable<IParser> BuildParsers();
}

public class UnityParserFactory : IParserFactory {
  private IUnityContainer _container;

  public UnityParserFactory(IUnityContainer container){
    _container = container;
  }

  public IEnumerable<IParser> BuildParsers() {
    return _container.ResolveAll<IParser>();
  }
}

public class Crawler {
  public Crawler(IParserFactory parserFactory) {
     // init here...
  }
}

有了这个,你可以按如下所示注册类型:

With this you can register the types as follows:

IUnityContainer container = new UnityContainer();

container.RegisterType<IParser, SuperParser>();
container.RegisterType<IParser, DefaultParser>();
container.RegisterType<IParser, BasicParser>();
container.RegisterType<IParserFactory, UnityParserFactory>();

Crawler crawler = container.Resolve<Crawler>();

这篇关于团结.NET:依赖列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆