Dependency Injection in ASP.NET Core MVC

This blog is going to explain what Dependency Injection(DI) is and how to implement it in ASP.NET core MVC. Dependency Injection is one of the best practice in ASP.NET Core MVC. The ASP.NET core has a lot of internal components, most of which are created using Dependency Injection. It allows you to create loosely coupled applications. This requires some extra code writing, but it can be useful for applications.

Let’s see step by step how to implement Dependency injection in ASPNet Core MVC

Step 1:
The following is a simple Movie class to store and display the result values. This Movie has three properties MovieName, ReleaseYear and Type

public class Movie
{
    public string MovieName { get; set; }
    public int ReleaseYear { get; set; }
    public string Type { get; set; }
}

Step 2:
Here I have created an interface called IMovieService and its one methoGetMovieDetails(). So the class that implements the IMovieService interface needs to implement the GetMovieDetails().

public interface IMovieService
{
    public Movie GetMovieDetails();
}

Step 3:
In this step, I have implemented the IMovieService interface in MovieService class. In GetMovieDetails() method, some values are assigned to display on the movie page.

public class MovieService : IMovieService
{
    public Movie GetMovieDetails() {

        Movie movie = new Movie() {
            MovieName = "The Lion King",
            ReleaseYear = 2019,
            Type = "Animated Films"
        };

        return movie;
    }
}

Step 4:
To use the dependency injection you must configure the interface and its implementation in the ConfigureServices method in the Startup.cs file. There are three ways to register your services. Singleton, Scoped, and Transient. It tells the DI how to create an instance when using it.
Singleton - This creates an instance for the first time of the request. The same instance is used whenever requested.
Scoped - This will create an instance for a scope. All requests within that scope will utilize that one instance.
Transient - This will always create a new instance for each request. I.e. each instance for each request.
Here Singleton method has been used.

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IMovieService, MovieService>();

    services.AddControllersWithViews();
}

Step 5:
This step is a Controller code. Here the controller class is connected to the interface, not to the implementation. You can see the IMovieService instance is passed by the Home controller construction. So there is no need to create an object using the new keyword. If implementation changes in the future, you do not need to worry about the IMovieService interface in the home controller. This is because the home controller depends on IMovieService, not implementation.

First, in the controller code, the _movieService variable is created. Then IMovieService instance movieService is injected into the home controller constructor. Finally, the GetMovieDetails() method is called using _movieService. So it returns the view with movie details.

public class HomeController : Controller
{
    IMovieService _movieService;

    public HomeController(IMovieService movieService)
    {
        _movieService = movieService;
    }

    public IActionResult Index()
    {
        return View(_movieService.GetMovieDetails());
    }
}

Step 6:
The final step is a view code. Here I have displayed the movie details.

Index.cshtml
@model Movie
Movie Name: <b> @Model.MovieName</b>
<br />
Release Year:<b>@Model.ReleaseYear</b>
<br />
Movie Type: <b>@Model.Type</b>

Output
The following is an output of the above code. It displays the movie details.

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Creating a C# Azure Function with Visual Studio: Step-by-Step Guide

Exploring EventCallback in Blazor: Building Interactive Components