Skip to content

Automatic collection registration

Isaac Abraham edited this page Jan 26, 2016 · 15 revisions

Automatic Collection Registration (ACR) is an enhancement on top of Multimaps that allows even easier access to collections of registrations, and is activated by using the AutomaticCollectionRegistration MappingBehaviour. Let's start with the following command pattern: -

[Multimap] public interface ICommand { }
class BackupCommand : ICommand { }
class QuitCommand : ICommand { }

Let's assume we wanted a simple CommandRunner class that would iterate through all commands and execute them in order. By default, the only way to access collections of registration in Unity is via the call to ResolveAll(). Let's also assume that the above commands have been registered into Unity as multimaps: -

container.AutomapAssemblies("MyAssembly");

class CommandRunner
{
   [Dependency]
   public IUnityContainer Container { get; set; }
      
   public void RunAll() {
      var commands = Container.ResolveAll<ICommand>();
      foreach (var command in commands)
      command.Execute();
   }
}

Note how we have had to add a dependency to the container itself and then call ResolveAll explicitly in order to retrieve the set of commands. This is where ACR comes in.

With ACR turned on, the command runner class can be simplified as follows: -

container.AutomapAssemblies(new MappingOptions(MappingBehaviours.AutomaticCollectionRegistration), "MyAssembly");

class CommandRunner
{
   [Dependency]
   public IEnumerable<ICommand> Commands { get; set; }
                 
   public void RunAll() {
      foreach (var command in commands)
         command.Execute();
   }
}

Essentially, the Automapper creates an IEnumerable<T> collection which yields out the results of ResolveAll<T>(), and registers that type itself into Unity.