In my previous article we discussed about the concept of dependency injection and inversion of control. Continuing on the same lines, we will now discuss how we can implement the dependency injection using the constructor injection. We will be using the same code which we used in our previous discussion.
As the name suggests itself, in this scenario, we use the constructors of the class, to inject the dependency into it. So we add a new parameterized constructor in the class. This parameter will be of type ILogger. So the abstraction gets passed to the class through the constructor, whenever an instance of the class is created. So our code changes to:
public class TestClass
{
ILogger logger;
public TestClass(ILogger iLogger)
{
logger = iLogger;
}
public void GetData()
{
try
{
//Get some data
}
catch (Exception ex)
{
logger.SaveException();
}
}
}
Now, when we call the GetData method, we will be creating a new instance of the class and pass the concrete implementation of ILogger i.e. DBLogger or TextLogger to the constructor. So the code will look like the following:
TestClass testClass = new TestClass(new TextLogger());
testClass.GetData();
That’s it. We are done with the code. Run the code and generate any exception and see the results. This is all we have to do to implement the constructor injection. In my next article, we will see how we can inject dependency using method injection. Happy coding...!!!
No comments:
Post a Comment