Search code examples
c#unity-container

C# Unity Dependency Injection, how can I retrieve an enumerable of instances?


I'm trying to register multiple instances of the same class so that when I inject an enumerable of that class, I retrieve all instances.

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
    }
}

So far i've got:

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;
    }
}

Can anyone show me how to do this?


Solution

  • Just register dependencies with names then resolve:

    ...
     container.RegisterInstance<IActionDialogType>("actionDialogType1", actionDialogType1, new ContainerControlledLifetimeManager());
    ...
     container.RegisterInstance<IActionDialogType>("actionDialogType2", actionDialogType2, new ContainerControlledLifetimeManager());
    
     var actionDialogTypeUser = container.Resolve<ActionDialogTypeUser>();
    

    Also constructor should have same types (interfaces in your case):

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