Skip to content
Isaac Abraham edited this page Jan 26, 2016 · 9 revisions

Multimaps are a powerful feature that allow you to easily include multiple implementations of the same interface into Unity. This is particularly useful for a number of situations: -

  • provider-style behaviour in your system where you may have many providers of a given interface.
  • pub-sub or visitor patterns
  • easily implementing the Command pattern

If you have several implementations of the same type, Unity allows you to register them all as "named registrations". This means in addition to the type mapping, you must register the mapping with a unique name, e.g.:

container.RegisterType<IMyCommand, ShutdownCommand>("First");
container.RegisterType<IMyCommand, PrintCommand>("Second");

// Gets back both ShutdownCommand and PrintCommand
IEnumerable<ICommand> commands = container.ResolveAll<ICommand>();

This allows an extremely flexible, decoupled architecture where you can write driver routines that operate over multiple types independently of the implementation of those types. Unity Automapper supports this type of behaviour by simply marking your interface as a Multimap: -

// Using attributes
[Multimap]
public interface ICommand { }
public class ShutdownCommand : ICommand { }
public class PrintCommand : ICommand { }

// Alternatively using the fluent API
AutomapperConfig.Create()
                .AndUseMultimappingFor(typeof(ICommand));

// Assume all three types live in MyAssembly
container.AutomapAssemblies("MyAssembly");
var commands = container.ResolveAll<IMyCommand>();

By default, the full name of the type is used for the registration name. Note that this customisation exists on the interface, not concrete implementations.