Click here to Skip to main content
14,241,414 members

Dependency Injection in ASP.NET Core 2.0

Rate this:
4.04 (13 votes)
Please Sign up or sign in to vote.
4.04 (13 votes)
19 Feb 2018CPOL
In this article we will see in detail on how to use Dependency Injection in ASP.NET Core 2.0. Now its much easier to use Dependency Injection in our ASP.NET Core application and the fact is that its very simple and use the result to bind in our View page

Introduction

In this article we will see in detail on how to use Dependency Injection in ASP.NET Core 2.0. Now its much easier to use Dependency Injection in our ASP.NET Core application and the fact is that its very simple and use the result to bind in our View page. Let’s see in details on how to create our ASP.NET Core project to use Dependency Injection for binding the student details to our View page. Hope you might be know about what is Dependency Injection and if you are curious to learn more detail about Dependency Injection then start from here  The Dependency Injection Design Pattern , Dependency injection in ASP.NET Core

Background

Prerequisites
Make sure you have installed all the prerequisites in your computer. If not, then download and install all, one by one.

  1. First, download and install Visual Studio 2017 from this link.

Using the code

Code Part

Now, it’s time to create our first Angular5 and ASP.NET Core application.

Step 1- Create ASP.NET Core Application

After installing the prerequisites listed above, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017, on your desktop.

Click New >> Project. Select Visual C# >> Select Angular5Core2. Enter your project name and click OK.

Select ASP.NET Core 2.0 , select  Web Application(Model-View-Controller) and click ok.

Our project will be created and its time for us to add a Class, Interface and Service for using Dependency Injection in ASP.NET Core application.

Step 2 – Creating Data Folder for Class

First, we will start with creating a class and for this from our project create a folder and name it as data as shown below.

Now we have created a folder named as Data in our project and next step will be to create a class named as “StudentDetails”. Right click the Data Folder and Add a new class named as “StudentDetails”

In Studentdetails class we create property as student name, Subjects and grade for each student like below.

public class StudentDetails
    {
        public string studentName { get; set; }
        public string Subject1 { get;  set; }
        public string Subject2 { get;  set; }
        public string Subject3 { get;  set; }
        public string Subject4 { get;  set; }
        public string Subject5 { get;  set; }
        public string Grade { get;  set; } 

    }

Now it’s time for us to create an interface with method named as GetAllStudentDetails() and we will be implementing this interface in our Service. For creating the Interface as we seen before add a new class to your data folder and name the class as “IStudentDetailService”.We will change the class to interface as we are going to create a interface to implement in our service. Here in this interface we declare a method as GetAllStudentDetails() with return type as IEnumerable

public interface IStudentDetailService
  {
      IEnumerable<StudentDetails> GetAllStudentDetails();
  }

Step 3 – Creating Service

First, we create a folder named as Services in project, right click your project and create a new folder as “Services”.

Now let’s add a new class in this folder and named as “StudentService” and in this class we will be implementing our Interface IStudentDetailService. We know that as if we implement the interface then we should the interface method in our class.In this service we use the interface method and we return the list with student details. We will be directly Inject this in our View page.

using ASPNETCOREDependencyInjection.Data;

namespace ASPNETCOREDependencyInjection.Services
{
    public class StudentService:IStudentDetailService
    {
         
        public IEnumerable<StudentDetails> GetAllStudentDetails()
        {
            return new List<StudentDetails>
        {
            new  StudentDetails {studentName = "Afreen", Subject1 = ".Net Programming",Subject2="Operating System",Subject3="Web Programming",Subject4="Networks",Subject5="C# & OOP",Grade="A"},
            new StudentDetails {studentName = "kather", Subject1 = ".Net Programming",Subject2="Operating System",Subject3="Web Programming",Subject4="Networks",Subject5="C# & OOP",Grade="A" },
            new StudentDetails {studentName = "Asha", Subject1 = ".Net Programming",Subject2="Operating System",Subject3="Web Programming",Subject4="Networks",Subject5="C# & OOP",Grade="A" },
            new  StudentDetails {studentName = "Afraz", Subject1 = ".Net Programming",Subject2="Operating System",Subject3="Web Programming",Subject4="Networks",Subject5="C# & OOP",Grade="B" },
            new  StudentDetails {studentName = "Shanu", Subject1 = ".Net Programming",Subject2="Operating System",Subject3="Web Programming",Subject4="Networks",Subject5="C# & OOP",Grade="C" }
            
        };
        }
    }
}

Step 4 – Register the Service

We need to register our created service to the container, Open the Startup.cs from your project to add our service to the container.

In the Startup.cs class find the method named as ConfigureServices and we add our service “StudentService” like below.

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<StudentService, StudentService>();

            services.AddMvc();
        }

Step 5 – Inject the Service in View page

Now it’s much simple and easier as we can directly Inject the service in our View page and bind all the result to our view page. For injecting the Service in our View, here we will be using our existing view page from Home >> Index.cshtml

In the “Index.cshtml” we inject our StudentService and bind all the result inside the table.

@inject ASPNETCOREDependencyInjection.Services.StudentService student

@if (student.GetAllStudentDetails().Any())
{
<table class='table' style="background-color:#FFFFFF; border:2px#6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2">
    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid1px#659EC7;">
        <td  align="center">
            Student Name
        </td>
        <td  align="center">
            Subject 1
        </td>
        <td   align="center">
            Subject 2
            </td>
            <td align="center">
                Subject 3
            </td>
            <td align="center">
                Subject 4
            </td>
            <td align="center">
                Subject 5
            </td>
            <td   align="center">
                Grade
            </td>
    </tr>
    @foreach (var std in student.GetAllStudentDetails().OrderBy(x => x.studentName))
    {
    <tr>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.studentName
            </span>
        </td>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.Subject1
            </span>
        </td>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.Subject2
            </span>
        </td>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.Subject3
            </span>
        </td>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.Subject4
            </span>
        </td>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.Subject5
            </span>
        </td>
        <td align="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
            <span style="color:#9F000F">
                @std.Grade
            </span>
        </td> 
    </tr>
   }
</table>
}

Step 6 – Build and Run the project

Build and run the project as we can see all our student’s details will be displayed in our home page.

 

Points of Interest

We can see clearly as now ASP.NET Core make’s our workload much simple and easy to use Dependency Injection  to directly Inject in our View page and bind the results.

History

ASPNETCOREDependencyInjection - 2018-02-15

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionGreat Pin
Mahsa Hassankashi15-Mar-18 1:11
memberMahsa Hassankashi15-Mar-18 1:11 
Suggestion[My vote of 1] Bad use of DI Pin
Grgmn21-Feb-18 14:39
professionalGrgmn21-Feb-18 14:39 
QuestionDI registration Pin
vladi721-Feb-18 2:21
membervladi721-Feb-18 2:21 
QuestionWhere is the Angular 5 Pin
John Gnazzo16-Feb-18 9:44
professionalJohn Gnazzo16-Feb-18 9:44 
AnswerRe: Where is the Angular 5 Pin
syed shanu21-Feb-18 23:02
mvasyed shanu21-Feb-18 23:02 
QuestionNice Article Sir Pin
Saineshwar Bageri14-Feb-18 19:04
member Saineshwar Bageri14-Feb-18 19:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 14 Feb 2018

Stats

10K views
193 downloads
19 bookmarked