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...!!!

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.

Dependency injection using constructor in C#

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...!!!

Dependency Injection and Inversion of control using C#

In this article, we will try to understand the concept of dependency injection and inversion control. The basic idea behind dependency injection is that:
  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.
These points here suggest that whenever we have a piece of code, where one class needs to use another class, for some functionality, the main class should not directly refer to the required class. It should always depend on the abstraction rather than its concrete implementation. Let’s see with an example what we mean over here:

public class TestClass  
{  
   ILogger logger;  
   public void GetData()  
   {  
     try  
     {  
        //Get some data    
     }  
     catch (Exception ex)  
     {   
        logger.SaveException();  
     }  
   }  
}  
    
public class Logger    
{    
   public void SaveException()    
   {    
      //Log the exception to textfile  
   }    
} 


Consider the piece of code above. Here, we have a test class, which executes the GetData function. In case any exception occurs, the catch block logs the error in a text file, using the SaveException method in the Logger class. So here we can see that the GetData method is directly dependent on the Logger class to save the exception to text file.

The above implementation seems to be fine until we have a requirement that we would like to save the exception to database, instead of the text file. In such a case, we will add another method and call that method say, SaveExceptionToDatabase. Further, if we need to save the exception in any other form, again we need to change the code in this class and then call that new method. So this will be a problem as we have to change the code whenever there is a new implementation and moreover, we may break the existing GetData method by these changes.


This is where the abstractions are useful. We implement the abstractions using the interfaces and main classes use these abstractions, which is nothing but the concept of Inversion of control, which is used to make a high level module dependent on the abstractions rather then the concrete implementations.

So in order to do this, we will change our code and add an interface named ILogger with a single method named SaveException. We also add two classes named DBLogger and TextLogger. Both these classes will implement the ILogger interface. So the code will change to:

public interface ILogger  
{  
  void SaveException();  
}  
  
public class DBLogger : ILogger  
{  
   public void SaveException()  
   {  
     //Save Exception to database  
   }  
}  
public class TextLogger : ILogger  
{  
   public void SaveException()  
   {  
      //Save Exception to text file  
   }  
}  

Next, we need to change the GetData function to use the dependency through abstraction instead of the concrete implementation. For this, we change the code to remove the Logger class instance and use the ILogger instance. So the code changes to: 

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

Now, the point is, we have changed the main class to use the dependency through interface, but how does the GetData receive the dependency i.e. the concrete implementation for ILogger which could be either DBLogger or TextLogger. This is where we have the concept of dependency injection. We will inject the dependency into the class. For this purpose, we can use the following three techniques.
  1. Constructor injectionInject the dependency through the constructor of the class.
  2. Method injectionInject the dependency through the method of the class, which requires dependency.
  3. Property InjectionInject the dependency through a property in the main class.
We will discuss these techniques in our next articles. For complex scenarios where we may have nested or multiple depdendencies, we have the concept of IoC containers to map the dependencies. Happy coding...!!!