I’m real fan of Unity, I already worked with other IoCs, but Unity remains my favorite.
In the upcoming posts, I will explain you how to :
In this post I will assume that you already know about ALL the advantages of using the IoC pattern. You can download Unity here.
First of all, we will create the project that will help us for all the samples. I will name it UnityTest.
First and foremost, let’s add a reference to Microsoft.Practices.Unity.
Then create an interface named IMyComponent:
Implement that interface in the MyComponent class:
Finally, implement Program as follows (register, then resolve the types):
What was actually done, was to instantiate the Unity container, and then register a new couple inside it. From then on, every time I will need an implementation of IMyComponent, Unity will instantiate MyComponent through a call to Resolve.
If I want to have MyComponent as a singleton, I will have to register it as an instance:
Then, each time I will need an instance of IMyComponent, Unity will return me the registered singleton.
I will create a new class MyComponentFr that will also implement the IMyComponent interface.
This is exactly the same code as the initial MyComponent except that the text is in French. The following code demonstrates how to use aliases to return different implementations of IMyComponent, depending on an alias :
As you can see, I just have to register the implementation with an alias.