Dependency Injection in ASP.NET Core

In this tutorial you will learn how to achieve Dependency Injection in ASP.NET Core Framework. dependency injection is one of the design patterns of SOLID principles.

// add following namespace in startup file

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
What is Dependency Injection?

Dependency Injection (DI) is a design pattern, using DI we can keep dependent objects outside of the class that depends on them, we can achieve loosely coupled design with the help of DI.

We must add namespace Microsoft.Extensions.DependencyInjection wherever we want DI to works.

.NET Core Dependency Injection Example

Let’s learn Dependency Injection in ASP.NET Core step by step

First we create a simple service interface called IAuthService and the implementation class AuthService, this class will have implementation of Data Transfer object which will have the final implementation of data access layer like ado.net or entity framework, that will be complete flow.

namespace WebTrainingRoom
{
    public interface IAuthService
    {
        User GetUser(string username, string password);
        User GetUser(string username);
    }


    public class AuthService : IAuthService
    {
        public User GetUser(string username, string password)
        {
            UserDTO dto = new UserDTO();
           return dto.GetUser(username, password);
        }
        public User GetUser(string username)
        {
            UserDTO dto = new UserDTO();
            return dto.GetUser(username);
        }
    }
}

Now we see how to AuthService class from controller without creating a explicit new instance

What I mean is, we will NOT create the instance like below!

public class userController : Controller
{
        AuthService _service=new AuthService();
}

Here we apply dependency injection through constructor in controller class like example below.

using AspnetCoreDAL.BO;
using AspNetCoreMVC.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace WebTrainingRoom.Controllers
{
    public class userController : Controller
    {
        IAuthService _authService;

        public userController(IAuthService authservice)
        {
            _authService = authservice;
        }

        public IActionResult index()
        {
            UserModel model = new UserModel();
            User u= _authService.GetUser(model.Username, model.Password);

            return View(model);
        }


        [HttpPost]
        public IActionResult index(UserModel model)
        {
           User u= _authService.GetUser(model.Username, model.Password);
            if (u != null)
            {
                SessionHelper.SetObjectAsJson(HttpContext.Session, "userObject", u);
                return RedirectToAction("controlpanel");
            }
            return View(model);
        }
       
    }
}

So far what you have seen, is actually almost the same as earlier example, now the difference will be how we register the service.

Service Registration in Startup file

Now we need to register the IAuthService service in middleware pipeline at startup.cs file.

In Asp.net core there us built-in IoC container, once you add the service with IServiceCollection instance, it automatically register the service with an IoC container.

So just register the service in ConfigureServices method like example below.

public void ConfigureServices(IServiceCollection services)
{
	services.AddSingleton<IAuthService, AuthService>();
}

The built-in IoC container in Asp.net core supports three type of lifetimes, by default it's singleton, like above example i have used AddSingleton method, when we don't specify the lifetime!

Like AddSingleton method, there is also AddTransient and AddScoped method.

services.AddTransient<IAuthService, AuthService>();
services.AddScoped<IAuthService, AuthService>();
  • Singleton method is just like singleton design pattern, it indicates that the IoC container will create one single instance of a service throughout the application's lifetime.
  • Transient indicates that the IoC container every time will create a new instance of that specified type. means new instance per request.
  • Scoped indicates, the container will create an instance of that service type once per request and will be shared.

The same service registration can also be done like example below.

public void ConfigureServices(IServiceCollection services)
{
    services.Add(new ServiceDescriptor(typeof(IAuthService), new AuthService())); //singleton


    services.Add(new ServiceDescriptor(typeof(IAuthService), typeof(AuthService), ServiceLifetime.Transient));


    services.Add(new ServiceDescriptor(typeof(IAuthService), typeof(AuthService), ServiceLifetime.Scoped));
}

Core concept of applying dependency injection will remain same, but how the unity container registration is done, that will defer from earlier version asp.net, you can look at my earlier post on dependency injection below.

Asp.Net Core C# Examples | Join Asp.Net MVC Course