Skip to content

Automatic collection registration

isaacabraham edited this page Dec 23, 2012 · 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 assume the following code: -

   public interface ICommand { }
   class BackupCommand : ICommand { }
   class QuitCommand : ICommand { }

And let's also 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(). First the automapping takes place: -

         container.AutomapAssemblies("MyAssembly");

Then the command runner: -

         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. First we perform automapping but this time with the behaviour: -

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

With ACR turned on, the command runner class can be simplified to this: -

             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 collection which yields out the results of ResolveAll(), and registers that type itself into Unity.

Clone this wiki locally