Understanding Dependency Injection (DI) in ASP.NET Core

0

 

Understanding Dependency Injection (DI) in ASP.NET Core

Introduction

Dependency Injection (DI) is a design pattern that helps achieve Inversion of Control (IoC) between classes and their dependencies. ASP.NET Core provides built-in support for DI, making it easier to manage dependencies and create loosely coupled, testable, and maintainable code.

What is Dependency Injection?

Dependency Injection is a technique where an object receives its dependencies from an external source rather than creating them internally. This promotes loose coupling and makes the code more modular and easier to test.

Why Use Dependency Injection in ASP.NET Core?

  1. Loose Coupling: DI helps in reducing dependencies between classes, making the code more modular and easier to maintain.
  2. Testability: DI makes it easier to mock dependencies during unit testing, leading to more reliable tests.
  3. Reusability: DI promotes the reuse of components, as dependencies can be easily swapped or changed.
  4. Separation of Concerns: DI helps in separating the creation of an object from its usage, leading to cleaner and more organized code.

How Does Dependency Injection Work in ASP.NET Core?

ASP.NET Core uses the IServiceProvider interface to manage dependencies. Services are registered with the DI container, and then injected into classes that need them.

Steps to Implement DI in ASP.NET Core

  1. Create an Interface: Define an interface that represents the dependency.
  2. Implement the Interface: Create a class that implements the interface.
  3. Register the Service: Register the service with the DI container in the Startup class.
  4. Inject the Service: Inject the service into the class that needs it using constructor injection.

Example: Implementing DI in ASP.NET Core

Step 1: Create an Interface

csharp

public interface IStudentService

{

    void AddStudent(Student student);

    IEnumerable<Student> GetAllStudents();

}

Step 2: Implement the Interface

csharp

public class StudentService : IStudentService

{

    private readonly List<Student> _students = new List<Student>();

 

    public void AddStudent(Student student)

    {

        _students.Add(student);

    }

 

    public IEnumerable<Student> GetAllStudents()

    {

        return _students;

    }

}

Step 3: Register the Service

In the Startup class, register the service with the DI container:

csharp

public class Startup

{

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddSingleton<IStudentService, StudentService>();

    }

}

Step 4: Inject the Service

Inject the IStudentService into a controller or another class:

csharp

public class StudentsController : Controller

{

    private readonly IStudentService _studentService;

 

    public StudentsController(IStudentService studentService)

    {

        _studentService = studentService;

    }

 

    public IActionResult Index()

    {

        var students = _studentService.GetAllStudents();

        return View(students);

    }

 

    [HttpPost]

    public IActionResult AddStudent(Student student)

    {

        _studentService.AddStudent(student);

        return RedirectToAction(nameof(Index));

    }

}

Advantages of Using Dependency Injection

  1. Improved Testability: DI makes it easier to mock dependencies during unit testing, leading to more reliable tests.
  2. Reduced Boilerplate Code: DI reduces the need for boilerplate code for creating and managing dependencies.
  3. Enhanced Modularity: DI promotes modularity by separating concerns and reducing dependencies between classes.
  4. Better Code Organization: DI helps in organizing code by separating the creation of objects from their usage.

 

Step 1: Create the Core Project

Create a new Core Web Application project. You can use Visual Studio, VS Code, or the .NET CLI to create the project.

sh
dotnet new mvc -n StudentManagement
cd StudentManagement

Step 2: Define the Student Model

Create a Student class in the Models folder.

Models/Student.cs

csharp
namespace StudentManagement.Models
{
    public class Student
    {
        public int RollNumber { get; set; }
        public string Name { get; set; }
    }
}

Step 3: Define the Student Service Interface and Implementation

Create an interface for the student service and its implementation.

Services/IStudentService.cs

csharp
using System.Collections.Generic;
using StudentManagement.Models;

namespace StudentManagement.Services
{
    public interface IStudentService
    {
        void AddStudent(Student student);
        IEnumerable<Student> GetAllStudents();
    }
}

Services/StudentService.cs

csharp
using System.Collections.Generic;
using StudentManagement.Models;

namespace StudentManagement.Services
{
    public class StudentService : IStudentService
    {
        private readonly List<Student> _students = new List<Student>();

        public void AddStudent(Student student)
        {
            _students.Add(student);
        }

        public IEnumerable<Student> GetAllStudents()
        {
            return _students;
        }
    }
}

Step 4: Register the Student Service in Dependency Injection

Register the StudentService in the Startup class.

csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using StudentManagement.Services;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddSingleton<IStudentService, StudentService>();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Step 5: Create the Students Controller

Create a controller to handle student operations.

Controllers/StudentsController.cs

csharp
using Microsoft.AspNetCore.Mvc;
using StudentManagement.Models;
using StudentManagement.Services;

namespace StudentManagement.Controllers
{
    public class StudentsController : Controller
    {
        private readonly IStudentService _studentService;

        public StudentsController(IStudentService studentService)
        {
            _studentService = studentService;
        }

        public IActionResult Index()
        {
            var students = _studentService.GetAllStudents();
            return View(students);
        }

        [HttpPost]
        public IActionResult AddStudent(Student student)
        {
            _studentService.AddStudent(student);
            return RedirectToAction(nameof(Index));
        }
    }
}

Step 6: Create the Views

Create views to display and add students.

Views/Students/Index.cshtml

html
@model IEnumerable<StudentManagement.Models.Student>

<h2>Student List</h2>
<table class="table">
    <thead>
        <tr>
            <th>Roll Number</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var student in Model)
        {
            <tr>
                <td>@student.RollNumber</td>
                <td>@student.Name</td>
            </tr>
        }
    </tbody>
</table>

<h2>Add Student</h2>
<form asp-action="AddStudent" method="post">
    <div class="form-group">
        <label for="RollNumber">Roll Number</label>
        <input type="text" class="form-control" id="RollNumber" name="RollNumber" />
    </div>
    <div class="form-group">
        <label for="Name">Name</label>
        <input type="text" class="form-control" id="Name" name="Name" />
    </div>
    <button type="submit" class="btn btn-primary">Add Student</button>
</form>

Running the Application

  1. Build and run the application.

  2. Navigate to /Students to see the list of students and add new students.

This example demonstrates how to set up a basic Core application using Dependency Injection with a Student model. The service is registered in the DI container and injected into the controller, following best practices for managing dependencies in Core.


https://shivaconceptsolution.com/.Net-training-in-indore-6




Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)