Dependency Injection in ASP.NET Core

Kasthuri Gunabalasingam
2 min readDec 26, 2020

Dependency Injection is the set of practices that allows to build loosely coupled applications. This is not a framework or tool, it is just a software design pattern, which is a technique for achieving loosely coupled mechanism among the software components.

ASP.NET Core framework contains a built-in Dependency Injection container it self. Prior to .NET Core, developers used Autofac, Ninject frameworks to achieve the Dependency injection.

public class HomeController : Controller
{
public IUserRepo _userRepo;
public HomeController()
{
_userRepo = new MockUserRepo();
}
public string Index()
{
return _userRepo.GetUser(1).Name;
}
}

Here HomeController has a dependency in IUserRepo ( an interface) and it’s implementation in MockUserRepo. HomeController is tightly coupled with MockUserRepo.

If any changes happens in MockUserRepo, HomeController need to be test again. In case IUserRepo decided to use another implementation (for example instead of MockUserRepo, use another implementation file called UserRepo), need to change all the controllers, which are using MockUserRepo dependencies. This is not an efficient way and difficult to manage as well. We can over come this issue using Dependency Injection in ASP.NET Core.

Let see how to achieve the dependency injection in ASP.NET Core.

public class HomeController : Controller
{
public IUserRepo _userRepo;
public HomeController( IUserRepo userRepo)
{
_userRepo = userRepo;
}
public string Index()
{
return _userRepo.GetUser(1).Name;
}
}

instead of creating dependency using ‘new’ keyword, inject IUserRepo in to the HomeController class using it’s constructor. To get IUserRepo implementation in to HomeController, we need to register the interface(IUserRepo) and it’s implementation(MockUserRepo) using ASP.NET Core Dependency Injection container in startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<IUserRepo, MockUserRepo>();
}

you can find the source code here.

--

--