• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Tuesday, May 29, 2018

What is Dependency Injection(DI)

 Abhishek Tomer     May 29, 2018     .Net, C#, Interview Question     2 comments   

Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it should be used.

Let's start with a question,
What is Dependency Injection(DI)?
DI is an architectural design pattern that helps us to convert (inject) all the dependent (couple) object into the independent (decouple) object means DI allow use to write loosely couple code and modules.
Advantages of De-coupled object or classes:
  • We can unit test an individual class that is dependent on other class or DB using the mock object.
  • We can change the implementation of service class at any time without breaking the host code.
  • We can be achieved extendibility by minimum modification and maintainability.
  • We can write loosely couple module.
DI can be implemented by injecting the Interface on:
  1. Constructor
  2. Properties
  3. Method

Tightly Coupled module:

In this example, I have taken the DAL, BAL, UI Layer example. In which these modules lightly depended on each other as given below.
UI ➨BAL ➨DAL

DAL:
namespace DIDemo.Couple.DAL
{
    public class SQLDAL
    {
        public void Save(string Name)
        {
            Console.WriteLine("student {0}:data saved into sql db”, Name);
        }
    }

    public class MYSQLDAL
    {
        public void Save(string Name)
        {
            Console.WriteLine("student {0}:data saved into mysql db”, Name);
        }
    }
}

BAL:
namespace DIDemo.Couple.BAL
{
    using DIDemo.Couple.DAL;
    public class StudentBAL
    {
        SQLDAL objSQLDAL;
        MYSQLDAL objMYSQLDAL;
       
        public void Save(string Name,int DBType)
        {
            //we can see that this class tightly cupled with
            //SQLDAL and MYSQLDAL class
            //save into SQL
            if (DBType==1)
            {
                objSQLDAL = new SQLDAL();
                objSQLDAL.Save(Name);

            }
            //save into MYSQL
            else if (DBType ==2)
            {
                objMYSQLDAL = new MYSQLDAL();
                objMYSQLDAL.Save(Name);
            }
        }

    }
}

Test Program:
namespace DI.Coupled
{
    using DIDemo.Couple.BAL;
    class Program
    {
        static void Main(string[] args)
        {
            //Create the instence of object
            StudentBAL studentObj = new StudentBAL();
            //Save into SQL db
            studentObj.Save("Student-1", 1);

            //Save into MYSQL db
            studentObj.Save("Student-1", 2);


            Console.ReadLine();
        }
    }
}

Description:
We can see that DAL is tightly coupled with BAL that’s why the modification is very difficult means if in future client required to save data into Oracle database then we need to create another class in Dal and create an object of Oracle class into BAL and write another if else code for Oral to save.

Now we can convert these coupled codes into decoupled code using Interface as below.

Loosely Coupled module:

Example of Dependency injection on the constructor.

DAL:
namespace DIDemo.ImpDeCouple.DAL
{
    public class SQLDAL : IDAL
    {
        public void Save(string Name)
        {
            Console.WriteLine("student {0}:data saved into sql db", Name);
        }
    }

    public class MYSQLDAL : IDAL
    {
        public void Save(string Name)
        {
            Console.WriteLine("student {0}:data saved into mysql db", Name);
        }
    }

    public interface IDAL
    {
        void Save(string Name);
    }
}

BAL:
namespace DIDemo.ImpDeCouple.BAL
{
    using DIDemo.ImpDeCouple.DAL;

    public class StudentBAL
    {
        IDAL objDAL;
        //Object is injected by somewhere else by other at run time.
        public StudentBAL(IDAL IDAL)
        {
            objDAL = IDAL;
        }

        public void Save(string Name)
        {
            objDAL.Save(Name);
        }

    }
}

Test Program:
namespace DI.ImpDeCouple
{
    using DIDemo.ImpDeCouple.DAL;
    using DIDemo.ImpDeCouple.BAL;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("DECOUPLED Example");

            //Create the instence of SQLDAL
            StudentBAL studentObj = new StudentBAL(new SQLDAL());
            //Save into SQL db
            studentObj.Save("Student-1");

            //Create the instence of MYSQLDAL
            StudentBAL studentObj = new StudentBAL(new MYSQLDAL());
            //Save into SQL db
            studentObj.Save("Student-1");


            Console.ReadLine();
        }
    }
}

Description:
we can see that BAL is Loosely coupled with DAL that’s we can modify the DAL class at any time because BAL expects the Interface into the constructor and instance of the class MYSQL and SQL will be provided by any third party in this call test class.

But object creation is still happed into the program class in UI to remove this we should use any third party tool that injects the instance at runtime.

DI can be resolved by any container like:
Unity, Ninject, Castle Windsor, Structure Map, Autofac and  Sping.Net

Implement Dependency injection using Unity resolver:
We need to install Unity using NuGet package manage and modify the UI layer code and all the code remain same.

Test Program:
namespace DI.ImpDeCouple
{
    using DIDemo.ImpDeCouple.DAL;
    using DIDemo.ImpDeCouple.BAL;
    using Unity;

    class Program
    {
        static void Main(string[] args)
        {
            //Create the instence of object
            IUnityContainer uc = new UnityContainer();
            uc.RegisterType<studentbal>();
            uc.RegisterType<idal sqldal="">();
            uc.RegisterType<idal mysqldal="">();
           

            StudentBAL studentObj = uc.Resolve<studentbal>();
            //Save into SQL db
            studentObj.Save("Student-1");

            Console.ReadLine();
        }
    }
}

Description:
We can see that whole module is loosely coupled and we can easy test and modify any module very easily by small modification.

Summary:
So, Guys, this is all about Dependency Injection in C#.
I Hope in this post covered all the points about how can we make our code loosely coupled which will be helpful to understand the concept Dependency Injection.

Please share this post with your friends and colleagues.
For any queries please post a comment below.

Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

2 comments:

  1. csharpbyrdMay 30, 2018 at 8:51 AM

    What abt di in method?

    ReplyDelete
    Replies
    1. C# TechticsMay 30, 2018 at 11:47 AM

      You can refer my new post on the given URL.
      Implementation of Dependency Injection Pattern using Methods in C#

      Delete
      Replies
        Reply
    2. Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape