Click here to Skip to main content
11,483,586 members (63,204 online)
Click here to Skip to main content

Dependency Injection

, 10 Apr 2013 CPOL 6.6K 49 6
Rate this:
Please Sign up or sign in to vote.
Concept Of Dependency Injection

Introduction

I believe pattern is anything in oops that solve problem domain. Dependency injection is way of implementing IOC. Dependency injection is not design pattern. Instead of having a class to create concrete object creation of other classes we specify that responsibility to any third party object that will give us concrete class object based on the need or during run time dynamically. Dependent class generally instantiates objects of all the classes on which he is dependent in the constructor call dependency. Instead of doing that we said the third party object to create all dependency base on the concrete class we inject into the third party object we get that class object on run time or on demand. I have implemented simple example that explain you how to implement dependency injection.

I have used the following way of implementing dependency injection.

  1. Setter getter way 
  2. This method commonly uses DI methodology. The dependency object are exposed through {set;get;} method of the classes. The object are publicly exposed it break the encapsulation rule of object oriented programming.

  3. Constructor way
  4. In this methodology we pass object reference in the constructor itself. This methodology is not suited for client who can only use only use default   constructor.

  5.  Interface implementation way 
  6. This methodology we implement and interface form the IOC framework. 

    IOC framework will use the interface method to inject the object in the main class. 

Background

I am validating XHTML5 item so I have instantiate validator class in constructor of the XHTML5 class.

public class XHTML5
{
    private Validator _validator;
    public XHTML5()
    {
        _validator = new Validator();
    }
}  

So I can use validate () method of the validator class that validate the XHTML5 item.

Pretty decent and works fine.

But as project progress we need to validate the XHTML5 item with different approach.

  1. DTD validation
  2. XSD validation
  3. Custom Validation 

There is possibility of validation type might be increase in future so there might be Custom XSD or Custom DTD etc.

So this brings in previous approach with following disadvantage. XHTML5 class creating Validator class objects. XHTML5 class is tightly couple with the Validator class. Any change in the validator class we need to update the XHTML5 class also. To implement change in the validator we are violating open and close principle. 

Using the code

Note you can implement following code using console application.

As we stated we have DTD, XSD and Custom validation method for XHTML5.

By Single responsibility principle let’s create separate class of it all classes contain logic to validate so let’s enforce general vocabulary using Interface to implement validation method.

public interface IValidator
{
    void validate();
} 
  1. DTD Validator  
  2. public class DtdValidator:IValidator
    {
        public void validate()
        {
            //for sec of simplicity I have avoided the logic.
            Console.WriteLine("Validating XHTML 5 using DTD validator.");
        }
    } 
  3. XSD Validator
  4. public class XsdValidator:IValidator
    {
        public void validate()
        {
            Console.WriteLine("Validating XHTML 5 using XSD validator.");
        }
    }
  5. Custom Validator
  6. public class CustomValidator:IValidator
    {
        public void validate()
        {
            Console.WriteLine("Validating XHTML 5 using cutom validator.");
        }
    }
    1. Let’s implement XHTML 5 using Constructor way
    2. We are injecting dependency into the constructor. 

      public class Xhtml5Consturctorway
      {
          private IValidator _validator;
          public Xhtml5Consturctorway(IValidator obj)
          {
              _validator = obj;
          }
          public void ValidateXhtml5()
          {
              _validator.validate();
          }
      } 
    3. Let’s implement XHTML5 using setter getter way
    4. Dependency object is exposing through set and get method.

      public class Xhtml5SetterGetterWay
      {
          private IValidator _validator;
          public IValidator Validator { get { return _validator; } set { _validator = value; } }
          public void ValidateXhtml5()
          {
              _validator.validate();
          }
      } 
    5. Let’s implement XHTML5 using interface way

      We implement interface where interface method use to inject the object in the main class.

    6. Interface contains method to use to inject the object in the main class.
      public interface IXhtml5InterfaceWay
      {
          void ValidateXhtml5(IValidator validate);
      } 

      Class implementing interface.

      public class Xhtml5InterfaceWay:IXhtml5InterfaceWay
      { 
          private IValidator _validator;
          public void ValidateXhtml5(IValidator validate)
          {
              _validator = validate;
              _validator.validate();
          }
      } 

      Class that uses the dependency injection.

      class Program
      {
          static void Main(string[] args)
          {
              #region Di using cunstructor methodology
              Xhtml5Consturctorway xhtml5Consturctorway = new Xhtml5Consturctorway(new XsdValidator());
              xhtml5Consturctorway.ValidateXhtml5();
              xhtml5Consturctorway = new Xhtml5Consturctorway(new DtdValidator());
              xhtml5Consturctorway.ValidateXhtml5();
              #endregion
              #region Di using setter getter way
              Xhtml5SetterGetterWay xhtml5SetterGetterWay = new Xhtml5SetterGetterWay();
              xhtml5SetterGetterWay.Validator = (new XsdValidator());
              xhtml5SetterGetterWay.ValidateXhtml5();
              xhtml5SetterGetterWay.Validator = (new CustomValidator());
              xhtml5SetterGetterWay.ValidateXhtml5();
              #endregion
              #region Di using interface way
              Xhtml5InterfaceWay xhtml5InterfaceWay = new Xhtml5InterfaceWay();
              xhtml5InterfaceWay.ValidateXhtml5(new DtdValidator());
              xhtml5InterfaceWay.ValidateXhtml5(new CustomValidator());
              #endregion
              Console.ReadLine();
          }
      }

Points of Interest  

I understand that design pattern are just implantation of OOPS concept. There is nothing complex in design pattern it is just oops concept name KIS [Keep It Simple]. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Amey K Bhatkar
Web Developer Lionbridge
India India
Amey K Bhatkar, a “Microsoft .Net” Web Developer.
I am programmer by will and profession.
I have completed my MCA in 2011 and join software industry.
Presently I am working with Lion Bridge Technologies in Mumbai - India
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 Pin
Anjum.Rizwi21-May-13 22:32
memberAnjum.Rizwi21-May-13 22:32 
GeneralRe: My vote of 5 Pin
Amey K Bhatkar25-May-13 9:41
professionalAmey K Bhatkar25-May-13 9:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 10 Apr 2013
Article Copyright 2013 by Amey K Bhatkar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid