• 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
Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday, August 20, 2020

Dependency Injection in C#

 Admin     August 20, 2020     .Net, C#, Design Patterns, Interview Question     No comments   

In this article, I am going to discuss the Dependency Injection in C# with examples. Please read our previous article where we discussed the Singleton Design Pattern in C# with some examples. Nowadays, the dependency injection design pattern is one of the most frequently used design patterns in real-time applications. So, as a developer, you should know why and how to use Dependency Injection Design Pattern in C#. We divided the dependency injection design pattern into three parts. As part of this article, we are going to discuss the following pointers in detail.
  1. Why Do We Need Dependency Injection in C#?
  2. What is Tight Coupling and Loose Coupling in Software Design?
  3. What is Dependency Injection Design Pattern in C#?
  4. Types of Dependency Injection Design Pattern in C#.
    Constructor Injection
    Property Injection
    Method Injection
  5. Example using Constructor Dependency Injection
What are the Advantages of Constructor Dependency Injection?
In part 2, we are going to discuss Property and Method Dependency Injection with examples. And in part 3, we are going to discuss the Unity Container in C# with an example.

Why do we need the Dependency Injection in C#?
The Dependency Injection is a design pattern that allows us to develop loosely coupled software components. In other words, we can say that this design pattern is used to reduce the tight coupling between the software components. As a result, we can easily manage future changes and other complexity in our application.

Before understanding the Dependency Injection Design Pattern using C#, first, we need to understand what is tight coupling and what is loose coupling in software development. So let’s understand these two concepts first.

What is Tight Coupling in Software Design?
Tight coupling means classes and objects are dependent on each other. That means when a class is dependent on another concrete class, then it is said to be a tight coupling between these two classes. In that case, if we change the dependent object, then we also need to change the classes where this dependent object is used. If your application is a small one, then it is not that difficult to handle but if you have a big enterprise-level application, then its really very difficult to handle to make these changes.

What is Loose Coupling in Software Design?
Loosely coupling means two objects are independent of each other. That means if we change one object then it will not affect another object. The loosely coupled nature of software development allows us to manage future changes easily and also allows us to manage the complexity of the application.

What is Dependency Injection Design Pattern in C#?
The Dependency Injection Design Pattern in C# is a process in which we are injecting the object of a class into a class that depends on that object. The Dependency Injection design pattern is the most commonly used design pattern nowadays to remove the dependencies between the objects.

Different Types of Dependency Injection in C#?
We can implement the Dependency Injection in C# in three different ways. They are as follows.

Constructor Injection: When we supply the dependency object through the client class constructor, then it is called as Constructor Injection.

Property Injection: When we supply the dependency object through the public property of the client class, then it is called as Property Injection.

Method Injection: When we supply the dependency object through a public method of the client class, then it is called as Method Injection.

Here, in this article, I will discuss how to inject the dependency object through the constructor. In the next article, I am going to discuss the Method and Property Dependency injection in C# with examples.

Constructor Dependency Injection in C#:
Let us understand the Constructor Dependency Injection in C# with an example. Let’s create a console application. to do so select, File => New => Project and then select the console application as shown below.
Dependency Injection Design Pattern in C#

Now create 3 classes Employee.cs, EmployeeDAL.cs and EmployeeBL.cs as shown below

Employee.cs
namespace DependencyInjectionExample
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}
EmployeeDAL.cs
namespace DependencyInjectionExample
{
    public class EmployeeDAL
    {
        public List<Employee> SelectAllEmployees()
        {
            List<Employee> ListEmployees = new List<Employee>();
            //Get the Employees from the Database
            //for now we are hard coded the employees
            ListEmployees.Add(new Employee() { ID = 1, Name = "Pranaya", Department = "IT" });
            ListEmployees.Add(new Employee() { ID = 2, Name = "Kumar", Department = "HR" });
            ListEmployees.Add(new Employee() { ID = 3, Name = "Rout", Department = "Payroll" });
            return ListEmployees;
        }
    }
}
EmployeeBL.cs
namespace DependencyInjectionExample
{
    public class EmployeeBL
    {
        public EmployeeDAL employeeDAL;
        public List<Employee> GetAllEmployees()
        {
            employeeDAL = new EmployeeDAL();
            return employeeDAL.SelectAllEmployees();
        }
    }
}
In the above example, in order to get the data, the EmployeeBL class depends on the EmployeeDAL class. In the GetAllEmployees() method of the EmployeeBL class, we create an instance of the EmployeeDAL (Employee Data Access Layer) class and then invoke the SelectAllEmployees() method. This is tight coupling because the EmployeeDAL is tightly coupled with the EmployeeBL class. Every time the EmployeeDAL class changes, the EmployeeBL class also needs to change.

Let us see how to use the constructor injection to make these classes loosely coupled.

Modify the EmployeeDAL.cs file as shown below
namespace DependencyInjectionExample
{
    public interface IEmployeeDAL
    {
        List<Employee> SelectAllEmployees();
    }
    public class EmployeeDAL : IEmployeeDAL
    {
        public List<Employee> SelectAllEmployees()
        {
            List<Employee> ListEmployees = new List<Employee>();
            //Get the Employees from the Database
            //for now we are hard coded the employees
            ListEmployees.Add(new Employee() { ID = 1, Name = "Pranaya", Department = "IT" });
            ListEmployees.Add(new Employee() { ID = 2, Name = "Kumar", Department = "HR" });
            ListEmployees.Add(new Employee() { ID = 3, Name = "Rout", Department = "Payroll" });
            return ListEmployees;
        }
    }
}
As you can see, first we create one interface i.e IEmployeeDAL with the one method. Then that interface is implemented by the EmployeeDAL class. So the point that I need to keep focus is when you are going to use the dependency injection design pattern in c#, then the dependency object should be interface based. In our example, the EmployeeDAL is the dependency object as this object is going to be used by the EmplyeeBL class. So we created the interface and then implement that interface.

Modify the EmployeeBL.cs file as shown below
namespace DependencyInjectionExample
{
    public class EmployeeBL
    {
        public IEmployeeDAL employeeDAL;
        public EmployeeBL(IEmployeeDAL employeeDAL)
        {
            this.employeeDAL = employeeDAL;
        }
        public List<Employee> GetAllEmployees()
        {
            Return employeeDAL.SelectAllEmployees();
        }
    }
}
In the above example, we created one constructor which accepts one parameter of the dependency object type. The point that you need to keep focus is, the parameter of the constructor is of the type interface, not the concrete class. Now, this parameter can accept any concrete class object which implements this interface.

So here in the EmployeeBL class, we are not creating the object of the EmployeeDAL class. Instead, we are passing it as a parameter to the constructor of the EmployeeBL class. As we are injecting the dependency object through the constructor, it is called as constructor dependency injection in C#.

Let’s us see how to use EmployeeBL class in our Main method of Program class:
namespace DependencyInjectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeBL employeeBL = new EmployeeBL(new EmployeeDAL());
            List<Employee> ListEmployee = employeeBL.GetAllEmployees();
            foreach(Employee emp in ListEmployee)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Department = {2}", emp.ID, emp.Name, emp.Department);
            }
            Console.ReadKey();
        }
    }
}
Now run the application and you will see the output as expected as shown below.
Dependency Injection in C#

Advantages of Constructor Dependency Injection
  1. The Constructor Dependency Injection Design Pattern makes a strong dependency contract
  2. This design pattern support testing as the dependencies are passed through the constructor.
In the next article, I am going to discuss the Property and Method dependency injection with some real-time examples. Here, in this article, I try to explain the Dependency Injection Design Pattern in C# steps by step with an example. I hope you understood the need and use of the Dependency Injection Design Pattern.

Summary:
I hope this post will be helpful to understand the concept of Dependency Injection in C#
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Older Posts

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