التخطي إلى المحتوى الرئيسي

Understanding Dependency Injection (DI) in ASP.NET Core

 

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




تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...