You don't need to create multiple named registrations. Named registrations are usually used when the named registration is different. e.g. different implementation type, or different dependencies, etc.
A factory implementation will work but, instead of creating a separate factory class, why not use Unity's InjectionFactory
? This saves creating a separate factory class and the service parameters can be the actual dependencies instead of an object that will be able to supply the dependencies. Another benefit is that the factory class is not dependent on Unity (assuming you want the factory class to use Resolve()
to construct the object graph of the objects the factory is returning).
In the example below then we can properly resolve an IWorker
without creating a factory class or passing an IUnityContainer
instance to a custom factory:
var container = new UnityContainer();
container.RegisterType<IWorker, Worker>();
container.RegisterType<List<IWorker>>(new InjectionFactory(c =>
{
var workers = new List<IWorker>();
for (var i = 0; i < 5; i++)
{
workers.Add(c.Resolve<IWorker>());
}
return workers;
}));
var service = container.Resolve<ServiceManagement>();
If different List<IWorker>
are required (e.g. one list for ServiceManagement and a different list for OrderManagement) then we could register different implementations for each and then wire them up by name to the correct Service:
var container = new UnityContainer();
container.RegisterType<IWorker, Worker>();
container.RegisterType<List<IWorker>>(typeof(ServiceManagement).Name,
new InjectionFactory(c =>
{
var workers = new List<IWorker>();
for (var i = 0; i < 5; i++)
{
workers.Add(c.Resolve<IWorker>());
}
return workers;
}));
container.RegisterType<List<IWorker>>(typeof(OrderManagement).Name,
new InjectionFactory(c =>
{
var workers = new List<IWorker>();
for (var i = 0; i < 20; i++)
{
workers.Add(c.Resolve<IWorker>());
}
return workers;
}));
container.RegisterType<ServiceManagement>(
new InjectionFactory(c => new ServiceManagement(c.Resolve<List<IWorker>>(typeof(ServiceManagement).Name))));
container.RegisterType<OrderManagement>(
new InjectionFactory(c => new OrderManagement(c.Resolve<List<IWorker>>(typeof(OrderManagement).Name))));
var service = container.Resolve<ServiceManagement>();
var order = container.Resolve<OrderManagement>();