C # Unity Dependency Injection, how can I get enumerated instances?

I am trying to register multiple instances of the same class so that when I introduce an enum from that class, I will 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 have:

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?

+3


source to share


2 answers


Just register dependencies with names , then solve:

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

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

      



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

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

      

+3


source


You should be able to resolve IEnumerable

dependencies with:

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

      

Since Unity understands an array, you are simply mapping an enumerated array to the same type. This will allow you to return a list of instances.



Then you can simply do the following:

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

      

0


source







All Articles