Register mappings as group

A while ago there was a question on the Unity discussion forum on how to handle a set of mappings as a logical group.

By the time I was neither happy with the implementation nor the API of my proof-of-concept but recently I found some time to improve it.

Consider having interfaces IVehicle, IEngine and IWheel and implementations thereof like Car, MotorCycleWheel and the like. You want to use the MotorCycle* implementations when you ask the container for a motorcycle (via container.Resolve<IVehicle>(“Motorcycle”)). But you don’t want so setup InjectionConstructors or ResolverOverrides.

var container = new UnityContainer();
container.RegisterGroup(c =>
  {
    c.RegisterType<IVehicle, Car>("Car");
    c.RegisterType<IWheel, CarWheel>();
    c.RegisterType<IEngine, CarEngine>();
  });
container.RegisterGroup(c =>
  {
    c.RegisterType<IVehicle, Motorcycle>("Motorcycle");
    c.RegisterType<IWheel, MotorcycleWheel>();
    c.RegisterType<IEngine, MotorcycleEngine>();
  });

var car = container.Resolve<IVehicle>("Car");
Assert.IsInstanceOfType(car.Wheel, typeof(CarWheel));
Assert.IsInstanceOfType(car.Engine, typeof(CarEngine));

var motorcycle = container.Resolve<IVehicle>("Motorcycle");
Assert.IsInstanceOfType(motorcycle.Wheel, typeof(MotorcycleWheel));
Assert.IsInstanceOfType(motorcycle.Engine, typeof(MotorcycleEngine));

The RegisterGroup extension method takes an Action<IUnityContainer> where you can setup the mappings that belong together. The first mapping needs to be named so that the rest of the mappings in the group can be identified properly. After that the mappings are resolved as a whole.

Get the source code for grouped mappings here (project TecX.Unity folder Groups and the test suite that shows how to use it in TecX.Unity.Test).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: