Grouped mappings

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 but recently I improved that first proof-of-concept.

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 (e.g. 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.

The code can be found in the TecX.Unity project (folder Groups).

Last edited Jun 25, 2012 at 11:02 AM by weberse, version 2

Comments

No comments yet.