Design Techniques with Constructor Injection

I will demonstrate the entire concept with clear examples that shows the difference between traditional implementation and new implementation.

Download Source Code.

Traditionally,

  1. publicinterfaceINewemp  
  2. {  
  3.    stringEmpID { getset; }  
  4.    stringEmpName { getset; }  
  5.    stringEmpAddress { getset; }  
  6.    DateTimeDateofJoining{ getset; } 
  7. }  
In the above interface we have properties for New Employees and the below interface has properties for Old Employee.
  1. publicinterfaceIOldemp  
  2. {  
  3.     stringEmpID  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     stringEmpName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     stringEmpAddress  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     DateTimeDateofJoining  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     DateTimeDateofReleaving  
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28. }  
See the difference carefully,

difference carefully

Just try to give implementation for it.

When you are trying to implement both interfaces, your class may get conflicts. Find Conflict section below

Find Conflict section

So what we do?

Solution1: Take two different classes and give implementation accordingly.

implementation

Finally your problem is clear for this time only. In future your project may have a chance to come with the same number of interfaces with duplicate properties. So find below solution2 for constructor injection for this problem.

Solution 2: Best solution (Constructor Injection),

Change your design pattern and come like this.

Program

Now you can give simple implementation without need of any second classes.

code

IOldEmp successfully implements INewemp properties also. Let’s check with practically.
  1. namespaceConstructorInjection.ConstructorTechnique.Injection  
  2. {  
  3.     publicclassConstructorInject  
  4.     {  
  5.         IOldempOldEmpData = newEmployee();  
  6.         publicINewempNewEmpData;  
  7.         publicConstructorInject()  
  8.         {  
  9.             NewEmpData = OldEmpData;  
  10.         }  
  11.     }  
  12. }  
And,
  1. classProgram  
  2. {  
  3.     staticvoid Main(string[] args)  
  4.     {  
  5.         var request = newConstructorInject();  
  6.         varActualResult = request.NewEmpData;  
  7.         Console.WriteLine("Actual values from Formal Object refrence");  
  8.         Console.WriteLine(ActualResult.EmpID);  
  9.         Console.WriteLine(ActualResult.EmpName);  
  10.         Console.WriteLine(ActualResult.EmpAddress);  
  11.         Console.Read();  
  12.     }  
  13. }  
run

Here I never Implemented INewemp interface. It is receiving implementation from IOldemp with the help of constructor injection.

For more information: TechNet (TN).