Dependency Injection for Beginners

Dependency Injection is a software development pattern to resolve the following problems. Below is a code that will better explain this:

Public class client
{
     Public static void main()
     {
        NeedDependencyClass a = new NeedDependencyClass();
     }
}

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass ()
  {
     _b = new DependencyClass();
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}

The problem with this code is that:

1. Class NeedDependencyClass is responsible for creating its own dependency.

2. Code violates the “Open Closed” rule of SOLID principal that says “software entities should be open for extension but closed for modification.

3. Code is tightly coupled because the dependency cannot be replaced.

4. Testing NeedDependencyClass becomes difficult because it cannot replace dependency class DependencyClass with other dependencies.

Read the solution in this blog: http://www.codeproject.com/Articles/719563/Dependency-Injection-For-Beginner-1

Leave a Reply

Your email address will not be published. Required fields are marked *