C#Unity依赖注入,如何检索可枚举的实例?

时间:2017-04-19 14:21:49

标签: c# unity-container

我试图注册同一个类的多个实例,这样当我注入该类的可枚举时,我会检索所有实例。

public class ActionDialogType
{
    public Type Type { get; set; }

    public string Name { get; set; }
}



public class ActionDialogTypeUser
{
    private IEnumerable<ActionDialogType> _types;
    public ActionDialogTypeUser(IEnumerable<ActionDialogType> types)
    {
        _types = types
    }
    public void DoSomethingWithTypes()
    {
        // Do Something with types
    }
}

到目前为止我已经:

public class UnityConfig
{
    public IUnityContainer Register()
    {
        UnityContainer container = new UnityContainer();

        ActionDialogType actionDialogType1 = new ActionDialogType
        {
            Name = "Something",
            Type = typeof(Something)
        };
        container.RegisterInstance<IActionDialogType>(actionDialogType1, new ContainerControlledLifetimeManager());

        ActionDialogType actionDialogType2 = new ActionDialogType
        {
            Name = "SomethingElse",
            Type = typeof(SomethingElse)
        };
        container.RegisterInstance<ActionDialogType>(actionDialogType2, new ContainerControlledLifetimeManager());
        container.RegisterType<IEnumerable<ActionDialogType>, ActionDialogType[]>();

        return container;
    }
}

有人能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:3)

只需使用名称注册依赖关系,然后解决:

...
 container.RegisterInstance<IActionDialogType>("actionDialogType1", actionDialogType1, new ContainerControlledLifetimeManager());
...
 container.RegisterInstance<IActionDialogType>("actionDialogType2", actionDialogType2, new ContainerControlledLifetimeManager());

 var actionDialogTypeUser = container.Resolve<ActionDialogTypeUser>();

构造函数也应该具有相同的类型(在您的情况下为接口):

public ActionDialogTypeUser(IEnumerable<IActionDialogType> types)
{
    _types = types
}

答案 1 :(得分:0)

您应该能够通过以下方式解析IEnumerable个依赖项:

container.RegisterType<IEnumerable<IActionDialogType>, IActionDialogType[]>();

由于Unity了解数组,因此您只需将可枚举数据映射到相同类型的数组即可。这将允许您返回实例的可枚举。

然后您可以简单地执行以下操作:

public class ExampleController : Controller
{
     private readonly IEnumerable<IActionDialogType> actionDialogType;
     public ExampleController(IActionDialogType actionDialogType)
     {
         this.actionDialogType = actionDialogType;
     }

     public IActionResult Get()
     {
         foreach(IActionDialogType instance in actionDialogType)
         {
              // Should expose via each now.
              var name = instance.GetType().Name;
         }
     }
}