I am trying to get Unity to manage the creation of my objects and I want to have some initialization parameters that are not known until run-time:
At the moment the
I also have come across this situation a few times in environments where I am dynamically creating ViewModel objects based on Model objects (outlined really well by this other Stackoverflow post).
I liked how the Ninject extension which allows you to dynamically create factories based on interfaces:
Bind
I could not find any similar functionality directly in Unity; so I wrote my own extension 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: UnityMappingFactory@GitHub
With a goal of simplicity and readability, I ended up with an extension that allows you to directly specify the mappings without declaring individual factory classes or interfaces (a real time saver). You just add the mappings right where you register the classes during the normal bootstrapping process...
//make sure to register the output...
container.RegisterType();
container.RegisterType();
//define the mapping between different class hierarchies...
container.RegisterFactory()
.AddMap()
.AddMap();
Then you just declare the mapping factory interface in the constructor for CI and use its Create() method...
public ImageWidgetViewModel(IImageWidget widget, IAnotherDependency d) { }
public TextWidgetViewModel(ITextWidget widget) { }
public ContainerViewModel(object data, IFactory factory)
{
IList children = new List();
foreach (IWidget w in data.Widgets)
children.Add(factory.Create(w));
}
As an added bonus, any additional dependencies in the constructor of the mapped classes will also get resolved during object creation.
Obviously, this won't solve every problem but it has served me pretty well so far so I thought I should share it. There is more documentation on the project's site on GitHub.