Go to Microsoft url to download Unity Framework
in the main :
we make a Console application in which we instantiate a simple class MyBusinessService and call an Execute method on it. This method only log usinge the Logger class in the solution.
the MyBusinessService class instantiate a logger class in execute method. We have a high dependence because MyBusinessService is responsible of the Logger Creation … So it will be hard to make good test because if we test execute the mistake can come from Logger Creation…
Logger class log on standard output (console):
In order to loose dependency between MyBusinessService and Logger, we will create an interface logger.Why ? Because we want through MyBusinessService to use not directly an instance of Logger object but use its interface. It will allow us to use Logger or any Logger which implement Ilogger interface.
Create a ILogger interface:
Now, modify MyBusinessService in order to use an interface ILogger instead of an instance. Create a property with a ILogger type :
the logger property is only an interface and we refer this interface ( for a good comprehension, I comment the instantiation of Logger object)
So now, MyBusinessService has losen the high dependency with Logger class by using an interface ILogger .
How and who will instantiate Logger class?
A third part, a Microsoft framework that will make a Dependency Injection : Unity.
Add a reference to Unity Framework
select Microsoft Practice Unity
we make four steps:
-first, create an instance of UnityContainer (namespace Microsoft.Practices.Unity)
-use registerType method to map interface and the class we want to use (this class have to implement this interface of course)
-use resolve method when you will need to use an instance of your desired class
-finally, pass this instance here by property, but you can also pass it in the constructor 😉
imagine now that we want to use another logger called logger2:
now we have only to change one line in our main program to pass logger2 instead logger class:
run it, it is incredible we use now our new class with little work: