Sunday, March 26, 2017

Dependency injection using method injection in C#

In my previous article, we discussed how we can inject the dependency using constructor. Continuing on the same lines, we will now discuss how we can implement dependency injection using the method injection. We will be using the same code which we used in our previous discussion.

The disadvantage with the constructor injection is that whenever we create an instance of the class, a new instance of the dependency gets generated and injected. It becomes available for all the method even though it was required for a single method only, as we are passing it through the constructor. So this is just not a good coding practice. So we can avoid this scenario by using the method injection.

In method injection, we change the actual method of the class (which requires dependency), to inject the dependency into it. The method will receive this dependency through parameter. So we add a new parameter to the GetData method. This parameter will be of type ILogger. So the abstraction gets passed to the class through the method itself. So our code changes to:

public class TestClass  
{  
        ILogger logger;  
   
        public void GetData(ILogger iLogger)  
        {  
            logger = iLogger;  
            try  
            {  
                //Get some data    
            }  
            catch (Exception ex)  
            {  
                logger.SaveException();  
            }  
        }  
}  


Now, when we call the GetData method, we will pass the concrete implementation of ILogger i.e. DBLogger or TextLogger to the method as a parameter. So the code will look like the following:

TestClass testClass = new TestClass();  
testClass.GetData(new DBLogger());  

That’s it. We are done with the code. This is all we have to do to implement the method injection. Run the code and generate any exception and see that the DBLogger method get's called.

No comments:

Post a Comment