Unity IoC container example
Feb 19, 2013 00:00 · 373 words · 2 minute read
What is Unity
It is an IoC container framework from Microsoft. You can download it from Nuget or codeplex .
What we have ?
We have a printer class that accepts printer type and do printing according to the passed type.
print class
public class Print {
private readonly ITypeOfPrinter _typeOfPrinter;
public Print(ITypeOfPrinter typeOfPrinter) {
_typeOfPrinter = typeOfPrinter;
}
public string print() {
return _typeOfPrinter.Printing();
}
}
The passed type can be Black and white or colorfull.
printer type
public class BlackAndWhitePrinter : ITypeOfPrinter {
public string Printing() {
NumberOfPrints++;
return string.Format("it is Black and white printing {0}",NumberOfPrints);
}
public int NumberOfPrints { get; set; }
}
How to use Unity
Using the Microsoft practice unity name space and make the Unity container object and registering the dependencies in order to resolve our concrete class.
unity container
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, ColorfullPrinter>();
var print = unityContainer.Resolve<Print>();
string colorfullText = print.print();
in this example we ask the constructor of the print class to use the colorfull printer type.
How to override the parameter
Sometime we need to override the the parameter that we have passed to our container.
default parameter
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, ColorfullPrinter>();
In this example we passed colorfullPrinter to the constructor but we need to change the passed type. In this case we can use ParameterOverride for registering the new type to the constructor.
override parameter
var print = unityContainer.Resolve<Print>(new ParameterOverride("typeOfPrinter",new BlackAndWhitePrinter()));
string colorfullText = print.print();
How to inject the property
If our dependency has the property and we need to initialize it before calling it. We can use UnjectProperty method .
inject property
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, ColorfullPrinter>();
unityContainer.RegisterType<ITypeOfPrinter, ColorfullPrinter>(new InjectionProperty("NumberOfPrints", 5));
var print = unityContainer.Resolve<Print>();
string colorfullText = print.print();
Unity singleton Lifecycle
By default every time we resolve a class with unity it make a new object of it, but sometimes we need to treat to our class as singleton to use its static properties.
singelton life cycle
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, ColorfullPrinter>(new ContainerControlledLifetimeManager());
var print = unityContainer.Resolve<Print>();
var print2 = unityContainer.Resolve<Print>();
In this case the printer and print2 has a different number of prints values.
Download
Feel free to download the full source code of this example from my GitHub.