View on GitHub

UnityMappingFactory

Extension which allows you to register factories that will create new objects based on data from different existing objects essentially mapping between them.

Download this project as a .zip file Download this project as a tar.gz file

UnityMappingFactory

Adds an Extension method to the IUnityContainer which allows you to register factories that will create new objects based on data from existing objects essentially mapping from one type hierarchy to a different type hierarchy.

The goal was simplicity and readability. No need to declare individual factory classes or even interfaces! Just add the mappings right where you register the classes during the normal bootstrapping process.

NOTE(s):

Example(s):

Simple 1-class to 1-class mapping:

//make sure to register the output...
container.RegisterType<IPersonViewModel, PersonViewModel>();

//define the mapping between classes...
container.RegisterFactory<IPerson, IPersonViewModel>()
    .AddDefaultMap();

This will map any IPerson instances as a parameter that will be used to create any instances of the IPersonViewModel.

Mapping between 2 different class hierarchies:

//make sure to register the output...
container.RegisterType<IImageWidgetViewModel, ImageWidgetViewModel>();
container.RegisterType<ITextWidgetViewModel, TextWidgetViewModel>();

//define the mapping between different class hierarchies...
container.RegisterFactory<IWidget, IWidgetViewModel>()
    .AddMap<IImageWidget, IImageWidgetViewModel>()
    .AddMap<ITextWidget, ITextWidgetViewModel>();

This will provide the following 2 mappings:

  1. The IImageWidget instances will be a parameter that will be used to create any instances of the IImageWidgetViewModel.

  2. The ITextWidget instances will be a parameter that will be used to create any instances of the ITextWidgetViewModel.

Details

Calling the RegisterFactory method actually creates an instance of a MappingFactory class and registers the instance of that class for the lifetime of the container. The class maintains a Dictionary of mappings that were added and utilizes the IUnityContainer.Resolve() method to create the requested object passing in the original object using the DependencyOverride parameter.