Dependency Injection in C#

Dependency Injection :- Dependency Injection is a Software Design Pattern mainly used for remove the dependency of Classes to each others.In short we can say that it is used for providing the Loosely Coupled System in which one class is not dependes on onther class so that we can easily manage the code.

By using Dependency Injection in application we can make our code more managable and readble and it provides better testability to application components.
With Dependency Injection we can easily enables the future changes and applied it in very easy way without more modifications of existing code.
ASP.Net core has a built-in support for Dependency Injections.

As its name suggest ,it injects the object of a class to outside that class and used in into a dependent class using three types of dependency techniques that is listed below.

  • Constructor Dependency Injection :- In this, depedency object/service objcet injects into the Client Class using the Client Class Constructor.
  • Property Dependency Injection :- Using the Public Property of the Client Class we can injcet the Dependency/Service Object into the Client Class.
  • Method Dependency Injection :- Using the Public Method of the Client Class we can injcet the Dependency/Service Object into the Client Class.

Below are some Implementation Guidlines for Dependency Injection to use into the application that we need to follow.

  • Create a Interface and define the methods that you want to use for data manipulations or any other business logic.
  • Create a Service Class and in the service class implement the Interface into this service class and provides the implementation for methods that are defined into the Interface.
  • Register this Service Class and Interface into the Service Collection with any one service method of AddSinglton/AddScoped/Addtransient inside the Program.cs file.
  • Create a Constructor in Client Class or inside the Controller where you want to use the dependent objects.

Practical Implementation for Dependency Injection :- For implementing the Dependency Injection in application firstly I have create a Interface in which i have declare a method StudentList() and it is returning the List of Student.So before creation of Interface create a Model Class and named it as Student as shown in below code snippet.

                
 public class Student
    {
        //Here we do not use data annotations this is only for example purpose
        public int StudentId { get; set; }
        public string StudentName { get; set; } 

        public int StudentAge { get; set; }
    }               
                

As shown in above code I have created a Student Model Class and after it I have created a Interface named it IStudent that you can find into below code snippet.

                
 public interface IStudent
    {
        List StudentList();
    }           
                

After creating a Interface now I have created a StudentService Class and implements the Interface into it and provides the implementation of StudentList() Method into this class.

                
 public class StudentService : IStudent
    {
        public List StudentList()
        {
            //Code is hard coded for example purpose you can get it from database also
            List students = new List()
            {
                new Student{StudentId=1,StudentName="John",StudentAge=22},
                new Student{StudentId=2,StudentName="Marry",StudentAge=24},
                new Student{StudentId=3,StudentName="Cristina",StudentAge=32},
                new Student{StudentId=4,StudentName="Jossef",StudentAge=20},
                new Student{StudentId=5,StudentName="Paul",StudentAge=27},
            };

            return students;

        }
    }
                 
                

After creating the Service Class and Interface we have to register this services into the Program.cs file with any one of the Service Life time methods(like AddScoped,AddSingleton,AddTransient) with Interface and Service class as depicted into the below code example.

                
using DIExamples.Repository;
using DIExamples.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddScoped();
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Student}/{action=StudentList}/{id?}");

app.Run(); 
                 
                

Now we have to use our dependency object into the Client Class or Controller using the Constructor Dependency so here I have created a constructor for Student Controller and pass IStudent Interface as a parameter into it and used a private readonly property for Interface and then further using this property we can call the methods of service class and it is completely loosely coupled.You can find the code from below example.

                
 public class StudentController : Controller
    {
        private  readonly IStudent studentService;

        public StudentController(IStudent student)
        {
            studentService = student;
        }
        [HttpGet]
        public IActionResult StudentList()
        {
            var st = studentService.StudentList();
            return View(st);
        }
    }
                 
                

Below is some screen images that I have attached for your reference and with these images you can easily understand the steps that we required for implementing the Dependency Injection and example code also. Below is the image for Solution Explorer after adding the folders and required class files.

Image is not available

Image of Program.cs file using the AddScoped services.

Image is not available

Image of Controller Class having Constructor Dependency code.

Image is not available

Image of code for cshtml file that is used for representing the Student data.

Image is not available

Image of final View that is used for representing the Student data.

Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.