0% found this document useful (0 votes)
23 views5 pages

dependency injection

The document discusses the Dependency Injection (DI) Design Pattern in ASP.NET Core, highlighting its importance for managing object dependencies and achieving loose coupling in software development. It provides a step-by-step guide for implementing DI in an ASP.NET Core MVC application, including creating models, interfaces, and service implementations. Additionally, it contrasts tight coupling with DI, emphasizing the benefits of using the built-in IoC container for dependency management.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views5 pages

dependency injection

The document discusses the Dependency Injection (DI) Design Pattern in ASP.NET Core, highlighting its importance for managing object dependencies and achieving loose coupling in software development. It provides a step-by-step guide for implementing DI in an ASP.NET Core MVC application, including creating models, interfaces, and service implementations. Additionally, it contrasts tight coupling with DI, emphasizing the benefits of using the built-in IoC container for dependency management.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

-The Dependency Injection Design Pattern is one of the most used design Patterns in

Real-Time Applications.

ASP.NET Core provides built-in support for dependency injection.

let us understand the Need for ASP.NET Core Dependency Injection

ASP.NET Core Dependency Injection (DI) is a powerful feature


that helps manage object dependencies within our application.

DI is a design pattern used to achieve loose coupling in software development.

Instead of creating dependencies (objects or services) directly within a class,

dependencies are injected into the class from outside, typically through
constructor parameters.

Let us understand this need for Dependency Injection Design Patterns in ASP.NET
Core Applications with an example.

--First, create a new ASP.NET Core Application named CoreMVCWebApplication with an


Empty Project Template.
--Once you create the ASP.NET Core Empty Project,
--let us add our models.
--To do so, first, create a folder with the name Models. Within the Models folder,
--let us add a class file with the name Student.cs, and this Student class will be
our model for this application.
--Then open the Student.cs class file and copy and paste the following code into
it.

namespace FirstCoreMVCWebApplication.Models
{
public class Student
{
public int StudentId { get; set; }
public string? Name { get; set; }
public string? Branch { get; set; }
public string? Section { get; set; }
public string? Gender { get; set; }
}
}

Creating Service Interface:


--Next,we create an interface named IStudentRepository.cs within the Models folder.

--This interface will declare the methods or operations we can perform on the
student data.
--So, open IStudentRepository.cs and copy and paste the following code.
--Here, you can see we have created the interface with two methods.

using System.Collections.Generic;
namespace FirstCoreMVCWebApplication.Models
{
public interface IStudentRepository
{
Student GetStudentById(int StudentId);
List<Student> GetAllStudent();
}
}
Creating Service Implementation:

--Next, create a class file named StudentRepository.cs within the same Models
folder.
--Then open the StudentRepository.cs class file and copy-paste the following code.
--This class implements the IStudentRepository interface by implementing the two
methods declared in the IStudentRepository interface.
--Here, we have hard-coded the student data, but you will get the student data from
a database in real-time applications.

using System.Collections.Generic;
using System.Linq;

namespace FirstCoreMVCWebApplication.Models
{
public class StudentRepository : IStudentRepository
{
public List<Student> DataSource()
{
return new List<Student>()
{
new Student() { StudentId = 101, Name = "James", Branch = "CSE",
Section = "A", Gender = "Male" },
new Student() { StudentId = 102, Name = "Smith", Branch = "ETC",
Section = "B", Gender = "Male" },
new Student() { StudentId = 103, Name = "David", Branch = "CSE",
Section = "A", Gender = "Male" },
new Student() { StudentId = 104, Name = "Sara", Branch = "CSE",
Section = "A", Gender = "Female" },
new Student() { StudentId = 105, Name = "Pam", Branch = "ETC",
Section = "B", Gender = "Female" }
};
}

public Student GetStudentById(int StudentId)


{
return DataSource().FirstOrDefault(e => e.StudentId == StudentId) ??
new Student();
}

public List<Student> GetAllStudent()


{
return DataSource();
}
}
}

--Program.cs:
In the Program class, we need to do two things.
--First, we need to configure the required MVC service to the IoC Container,
--and then we need to add the MVC Middleware to the request processing pipeline.
So, modify the Program class as shown below.

namespace FirstCoreMVCWebApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMvc();

var app = builder.Build();

app.UseRouting();

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

app.Run();
}
}
}

Without Dependency Injection:


--Create a folder named Controllers in your project.
--Then, add a class file named HomeController.cs within the Controllers folder and
copy-paste the following code.
--Here, you can see that within the Index and GetStudentDetails action methods, we
are creating an instance of the StudentRepository class and calling the respective
methods.

using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace FirstCoreMVCWebApplication.Controllers
{
public class HomeController : Controller
{
public JsonResult Index()
{
StudentRepository repository = new StudentRepository();
List<Student> allStudentDetails = repository.GetAllStudent();
return Json(allStudentDetails);
}

public JsonResult GetStudentDetails(int Id)


{
StudentRepository repository = new StudentRepository();
Student studentDetails = repository.GetStudentById(Id);
return Json(studentDetails);
}
}
}
--With the above changes in place, now run the application and check the above two
methods. it should work as expected,

What is the Problem with the above implementation?


As you can see in the above HomeController class, it depends on an instance of the
StudentRepository class to get student data. Here, within the HomeController class,
we create an instance of the StudentRepository class and invoke the
GetStudentById() and GetAllStudent methods. This is tight coupling because the
HomeController class is now tightly coupled with the StudentRepository concrete
class.

Tomorrow, if the implementation class of the IStudentRepository is changed from


StudentRepository to TestStudentRepository, then we also need to make the changes
to the code in the HomeController class, as they are both tightly coupled. We can
overcome this problem by implementing the Dependency Injection Design Pattern.

What is the Dependency Injection (DI) Design Pattern?


Dependency Injection is the process of injecting the dependency object into a class
that depends on it.

It is the most commonly used design pattern nowadays to remove the dependencies
between objects, allowing us to develop loosely coupled software components.
--

Let us discuss the step-by-step procedure for implementing dependency injection in


the ASP.NET Core MVC application.

The ASP.NET Core Framework is designed from scratch to provide built-in support for
dependency injection design patterns. It injects dependency objects into a class
through a constructor or method using the built-in IoC (Inversion of Control)
container. The built-in IoC (Inversion of Control) container is represented by
IServiceProvider implementation, which supports default constructor injection. The
types (i.e., classes) managed by built-in IoC containers are called services.

Types of Services in ASP.NET Core:


There are two types of services in ASP.NET Core. They are as follows:

Advertisements
Framework Services: Services that are a part of the ASP.NET Core Framework, such as
IApplicationBuilder, IHostingEnvironment, ILoggerFactory, etc.
Application Services: The services (custom types or classes) you create as a
programmer for your application.

You might also like