Unity and dependence on the collection of objects

In my case, a certain class does not depend on one object, but on its collection:

public class ImportController { ...
public ImportController(IEnumerable<IImportManager> managers) { ... }
}

public class ProductAImportManager : IImportManager { ... }
public class ProductBImportManager : IImportManager { ... }
public class ProductCImportManager : IImportManager { ... }

I want to create an instance of ImportController using Unity, so how do I register dependencies?

If I use something like

unityContainer.RegisterType<IImportManager, ProductAImportManager>();
unityContainer.RegisterType<IImportManager, ProductBImportManager>();

the second call simply overrides the first.

Can I ask Unity to find all registered types that implement the IImportManager interface, create these types and pass a sequence of objects to my constructor?

+5
source share
2 answers

Unity has some fancy permission rules when it comes to multiple registrations.

  • , (.. container.RegisterType<IInterface, Implementation>()), container.Resolve.

  • container.ResolveAll<IInterface>().

, , , - , ResolveAll :

public static class UnityExtensions {  
   public static void RegisterCollection<T>(this IUnityContainer container) where T : class {
    container.RegisterType<IEnumerable<T>>(new InjectionFactory(c=>c.ResolveAll<T>()));
  }
}

.

//First register individual types
unityContainer.RegisterType<IImportManager, ProductAImportManager>("productA");
unityContainer.RegisterType<IImportManager, ProductBImportManager>("productB");
//Register collection
unityContainer.RegisterCollection<IImportManager>();
//Once collection is registered, IEnumerable<IImportManager>() will be resolved as a dependency:
public class ImportController { ...
  public ImportController(IEnumerable<IImportManager> managers) { ... }
}
+5

, :

unityContainer.RegisterType<IImportManager, ProductAImportManager>("a");
unityContainer.RegisterType<IImportManager, ProductBImportManager>("b");


public class ImportController { ...
   public ImportController(IImportManager[] managers) { ... }
}
+3

All Articles