Posts Tagged IoC

Dependency Injection

Sample code can be downloaded from here.

First – What is a dependency?
– We are talking about a class (say “ATest”) which needs another class (say “BTest”) to call Its (“ATest”) methods (See below example). Therefore, class “BTest” is a dependency for class “ATest”.

public class BTest
{
     public int DoBTestWork()
     {
           // Do some work
     }
}

public class ATest
{
        private readonly BTest bTest;  // Dependency
        public ATest() 
        {
            bTest = new BTest();
        }
        public void DoATestWork()
        {
            var  bTestOutput = bTest.DoBTestWork();
            // Do something with bTestOutput
        }      
}

image

 

Can we try decoupling class ATest and BTest.
Yes – try interfaces. Here in the below example. We have the same classes as above. However – this time we have the method in BTest coming from the interface IBTest. Class ATest is now have the object reference of interface IBTest instead of BTest class.

public interface IBTest
{
     int DoBTestWork()
}
public class BTest : IBTest
{
    public int DoBTestWork()
   {
   // Do some work
   }
}

public class ATest
{
    private readonly IBTest bTest;
    void ATest()
    {
      bTest = new BTest();
   }

   public void DoATestWork()
   {
      var bTestOutput = bTest.DoBTestWork();
     // Do something with bTestOutput
    } 
}

Is this good enough? No. Because we we still have the reference of BTest in the ATest class. See – the even though the object bTest is of type IBTest, It is getting instantiated from BTest. So the classes – ATest and BTest are still not decoupled.

image

What is Dependency injection?
– It’s a type of IoC which let us take out the dependencies of a class and handles their (dependencies) creation and binding. This way the class no longer has to have the references of the dependencies.

How to we implement it :-

  • Constructor Injection
  • Property/Setter Injection
  • Method Injection

Constructor Injection
Pass dependency into the dependent class via the constructor. Here, the constructor on ATest is taking an interface of IBTest and we don’t have any reference of the concrete class BTest.

public interface IBTest
{
        int DoBTestWork()
}

public class BTest : IBTest
{
          public int DoBTestWork()
          {
             // Do some work
          }
}

public class ATest
{
         private readonly IBTest bTest;
         void ATest (IBTest bTest)
         {
           this.bTest = bTest;
          }

          public void DoATestWork()
          {
            var bTestOutput = bTest.DoBTestWork();
            // Do something with bTestOutput
          } 
}

Following is the code which would call use ATest and pass the its dependency BTest in it.

IBTest bTest = new BTest();
ATest aTest = new ATest(bTest);
aTest.DoATestWork();

Property/Setter Injection
Don’t pass dependency in the constructor of the dependent class. Just have the interface dependency types as public properties in the dependent class.

public interface IBTest
{
       int DoBTestWork()
}

public class BTest : IBTest
{
       public int DoBTestWork()
      {
       // Do some work
      }
}

public class ATest
{
       public IBTest BTestObject { get; set; }
       public void DoATestWork()
       {
         var bTestOutput = BTestObject.DoBTestWork();
        // Do something with bTestOutput
        } 
}

Following is the code which would call use ATest. It just sets the the public property of dependency interface type (IBTest) to the concrete type(BTest).

IBTest bTest = new BTest();
ATest aTest = new ATest();
aTest.BTestObject = bTest;
aTest.DoATestWork();

We should use this have some optional properties and having those properties not assigned won’t impact calling methods.

Method Injection
Don’t pass dependencies in the constructor or set them on the properties of the dependent class. Just pass them in the method of the dependent class.

public interface IBTest
{
   int DoBTestWork()
}

public class BTest : IBTest
{
     public int DoBTestWork()
     {
        // Do some work
     }
}

public class ATest
{
       public void DoATestWork(IBTest bTest)
       {
          var bTestOutput = bTest.DoBTestWork();
         // Do something with bTestOutput
       } 
}

Following is the code which would call use ATest. It just passes the dependency interface type (IBTest) to the dependent ATest method DoATestWork.

ATest aTest = new aTest();
IBTest bTest = new BTest();
aTest.DoATestWork(bTest);

, ,

2 Comments

Inversion of Control (IoC)

image

  • Dependency Inversion Principle (DIP) – Principle of inverting dependencies in software architecture.
  • Inversion Of Control (IoC) – Pattern which uses DIP.
  • Dependency Injection (DI) – An Implementation of IoC (but there are many other ways to implement IoC).
  • IoC Container – Framework to implement IoC.

Dependency Inversion Principle :-
The higher level modules define interfaces which lower level modules implement. This needs to be done instead of higher level modules depending and using the interfaces which lower level modules expose.

Example :- The computer is a high level device/module. It has an USB port – the interface exposed – to which all other (low level modules) devices e.g iPhone, mouse, Keyboard can plug into. The computer can make use of any device as long as that device can connect to the USB port.

Inversion of Control :-
Provide ways to implement DIP.

  • Interface Inversion
  • Dependency Creation/Binding Inversion
        • Factory methods
        • Service Locator
        • Dependency Injection

Interface Inversion :-
Suppose we have following classes :-
ATest, BTest1, BTest2, BTest3

BTest1, BTest2 and BTest3 do similar BTest type of work which they have implemented with DoB1Work(), DoB2Work() and DoB3Work() respectively.
Now class ATest needs to call public methods (interface) of BTest1, BTest2 and BTest3 separately. Here Class “ATest” is the consumer and all those B classes are providers.

public class ATest
{
    public void DoSomeAWork()
    {
         BTest1 b = new BTest1();
         b.DoSomeBWork();
         // Do something else
    }
}
public class BTest1
{
     public void DoSomeBWork()
     {
          // Do something          
     }
}

So here, the consumer (ATest) needs to know about each provider (BTest1, BTest2 and BTest3). The “control” here is in providers’ (B classes) hand because they are defining interfaces (public methods) which the consumer needs to call and need to be changed If the public method changes.

What should really happen – We create an interface IBTest having one method DoBWork() which would be implemented by all the B classes with their own concrete implementation. Here we inverted the control. The control is in consumer’s (Class A) hands now.

Now we end up having something like below in Class ATest.

IBTest bTest = new B1Test();

Now with above, we are still instantiating a concrete class (B1Test) and this makes the ATest (Consumer) dependent on class B1Test (Provider).

Dependency Creation/Binding Inversion patterns
These patterns let creation of dependencies to be done by another class. Following are the ways to do it.

a) Factory Pattern
b) Service Locator
c) Dependency Injection

Leave a comment

Random Thoughts

The World as I see it

Simple Programmer

Making The Complex Simple

Ionic Solutions

Random thoughts on software construction, design patterns and optimization.

Long (Way) Off

A tragic's view from the cricket hinterlands