Jan 8 2008

Dependency Injection explained

Category: C# | Patternsfossmo @ 11:35

Dependency Injection (DI) is a fancy word for a very simple pattern. You probably use DI at some sort every time you code. In it simplest form, a variable is injected into a method and the method can interact with the variable. That's DI.

I often use DI in a other pattern called Model View Presenter. 

In the figure below, I visually try to show how DI works.

DependencyInjection

(Click on the image to view larger)

Below is a example of how I often use the pattern.

   1:  namespace DependencyInjection
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {
   7:              Class1 class1 = new Class1();         
   8:          }
   9:      }
  10:   
  11:      public interface IProperties
  12:      {
  13:          string MyValue { get; set; }
  14:      }
  15:   
  16:      public class Class1:IProperties
  17:      {
  18:          string _myValue = "Class1 value";
  19:          Class2 class2;
  20:   
  21:          public Class1() 
  22:          {
  23:              Console.WriteLine(MyValue);
  24:              class2 = new Class2(this);
  25:              class2.ChangeMyValue();
  26:              Console.WriteLine(MyValue);
  27:              Console.ReadKey();
  28:          }
  29:   
  30:          public string MyValue
  31:          {
  32:              get
  33:              {
  34:                  return _myValue;
  35:              }
  36:              set
  37:              {
  38:                  _myValue = value;
  39:              }
  40:          }     
  41:      }
  42:   
  43:      public class Class2
  44:      {
  45:          private IProperties _view;
  46:   
  47:          public Class2(IProperties view)
  48:          {
  49:              _view = view;
  50:          }
  51:   
  52:          public void ChangeMyValue()
  53:          {
  54:              _view.MyValue = "Changed by instance of Class 2";
  55:          }
  56:      }
  57:  }
 
 
 
In line 7, a instance of Class 1 is created. The constructor in Class 1 is executed (line 21). 
Class 2 is called with the instance of the current object (Class 1). 
This is possible because Class 1 implements the interface IProperties (line 11). In line 25, class 2
calls the method ChangeMyValue. The property MyValue in Class 1 is changed.
 
That's the dependency injection pattern.
 

Tags:

Currently rated 3.0 by 4 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Comments are closed