Sunday, March 26, 2017

Dependency injection using property in C#

In my previous articles, we discussed how we can inject the dependency using constructor and method. This is the final approach we can use to inject the dependency where we will see how we can implement the dependency injection using the property injection. We will be using the same code which we used in our previous discussions.

In property injection, we simply create a property of the type of dependency required by our class. Whenever we need to call a method which needs a dependency to be used, we set the property of the class, to the required concrete implementation of the dependency. In our case, we will create a property named logger which is of type ILogger, in the TestClass. So our code changes to:

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

Now, when we call the GetData method, we will set the concrete implementation of ILogger i.e. DBLogger or TextLogger to the logger property defined in the class. So the code will look like the following:

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

That’s it. We are done with the code. This is all we have to do to implement the property injection. Run the code and generate and exception and see the results. 

This is not a much used approach, but it is useful in situations where we need to avoid the use of constructor injection, similar to the method injection. Hope you enjoyed reading these three methods. Happy coding...!!!

No comments:

Post a Comment