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.
//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.
//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:
The IImageWidget instances will be a parameter that will be used to create any instances of the IImageWidgetViewModel.
The ITextWidget instances will be a parameter that will be used to create any instances of the ITextWidgetViewModel.
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.