How to use dependency injection in ASP.Net Core


Support for dependency injection is built into ASP.Net Core, Microsoft’s open source, cross platform, lean, and modular framework for building high performance, scalable web applications. In ASP.Net Core, both framework services and application services can be injected into your classes, rather than being tightly coupled. In this article we’ll look at how we can work with dependency injection in ASP.Net Core.

Dependency injection (also known as DI) is a design pattern in which a class or object has its dependent classes injected (passed to it by another class or object) rather than create them directly. Dependency injection  facilitates loose coupling and promotes testability and maintenance. Moreover, dependency injection allows you to change your implementations without having to change the classes or interfaces that leverage those implementations.

Making a service available via dependency injection in ASP.Net

We will now build a simple service in Visual Studio using ASP.Net Core and illustrate how we can add it to the dependency injection container, register it with the pipeline, and then consume it in our application. Follow these steps to create a new ASP.Net Core project in Visual Studio 2017 or Visual Studio 2015. If you’re using Visual Studio 2015, make sure you have .Net Core installed.

  1. Open Visual Studio
  2. Click File -> New -> Project
  3. In the New Project Dialog Window, select the “ASP.NET Core Web Application” project template
  4. Specify the name and location for your project and click OK to save

Now, create the following POCO (plain old CLI object) class. This class contains just one property – it represents all of the topic areas covered by the authors of a particular publishing company.