Search code examples
c#unity-container

C# Unity register a list of registered types and resolve by adding N instances


I have a service that receives a

 public ServiceManagement(List<IWorker> workers)

And I have the workers registered:

this.Container.RegisterType<IWorker, Worker>

I would like to tell unity when resolving that list to create exactly N instances of Worker.

Anyone can help?

I tried the following:

Receiving an array instead of a List and registering like so:

for (int i = 0; i < N; i++)
{
    this.Container.RegisterType<IWorker, Worker>(i.ToString());
}

But this only works for different implementations of IWorker not the same.

Thanks in advance!


Solution

  • I ended up doing this way,

    Creating a factory doesn't solve the dependencies of the worker class unless you pass them to the factory itself, which would mean have a factory for each type of worker which adds too much overhead.

    Could be done by resolving N times the Worker when registering the type, and registering the List with those instances, but that will make the resolving dependent on the order of the RegisterType, which is also bad. It would also resolve the instances before you actually needed them.

    Eventually I did an InjectionFactory:

    this.Container.RegisterType<List<IWorker>>(new InjectionFactory(c =>
            {
                var workers = new List<IWorker>();
    
                for (int i = 0; i < N; i++)
                {
                    workers.Add(c.Resolve<IWorker>());
                }
    
                return workers;
            }));
    

    This way it will only resolve the instances when needed and Unity will take care of resolving IWorker dependencies on its own.