Basic Constructor Injection using Interfaces

Using interfaces is potentially the easiest way to provide extensible classes, i will try and demonstrate a very basic way to performing this technique.

Lets start by defining a basic interface, this will be the basic implementation; remember, you cannot define functionality in a interface. What we are doing is defining a “contract” with the objects that are going to consume it.

 
public interface IInformation{
    void MyMethod(string input);
}

Now lets create a basic class

 
public class DoStuff{

}

lets extend the class by adding a new public method called MyTestMethod; this shall take a string as its only input argument.

 
public class DoStuff{
   public void MyTestMethod(string input){

   }
}

I want the DoStuff class to be a “Consumer” of the IInformation interface so i will create a new constructor on the class which accepts the IInformation interface as a constructor parameter.

 
public class DoStuff{
   private IInformation _context {get;set;}

   public DoStuff(IInformation context){
       _context = context;
   }

   public void MyTestMethod(string input){
       _context.MyMethod(input);
   }
}

So now we have a constuctor which accepts the interface IInformation. You will notice that the input argument is assigned to a private property of the same interface, this is so that we can reference it later. Also notice that the MyTestMethod calls MyMethod, this is the method used in the interface definition.

So how can we use the interface to provide a means of injection. Well, first lets create two simple classes which implement the IInformation interface.

 
public class SayHello : IInformation{
   public void MyMethod(string input){
     Console.WriteLine("Hello " + input);
   }
}

public class SayGoodBye : IInformation{
   public void MyMethod(string input){
     Console.WriteLine("GoodBye " + input);
   }
}

these classes could provide totally different functionality. But how do we use these classes with our DoStuff class. Well because we have implemented the IInformation interface on the two classes then can be accepted as input types to the DoStuff constructor.


DoStuff tmp1 = new DoStuff(new SayHello());
DoGoodBye tmp2 = new DoStuff(new SayGoodBye()); 
 

So, we have passed new instances of the two classes into the constructor of our main class. We can now call the MyTestMethod.

 
tmp1.MyTestMethod("Sam Smith");
tmp1.MyTestMethod("Sam Smith");

The output of this will be:
Hello Sam Smith
GoodBye Sam Smith

So as you can see, we have a single point of reference, we call the DoStuff’s MyTestMethod and dependent on the constructor parameter we get different results.

This is a very basic example of constuctor injection, its a simple concept but a powerful one once you understand the possibilities.

Hope this made sense 🙂