Leveraging Dependency Injection In Asp.Net Core

Introduction

In any modern application lifecycle, code efficiency and maintainability stand out as key factors making an application easy to manage and scars-free of bugs. A good practice to improve our application in these terms is the principle of Dependency Injection (DI).

What is Dependency Injection?

Dependency Injection is a software design pattern that focuses on the principle of Inversion of Control (IoC). According to this principle, an object should not configure its own dependencies (or how to get them). Instead, dependencies should be injected in the object (usually by an IoC container) directly.

Its conceptual implementation in ASP.NET Core

ASP.NET Core supports innate DI and aims to use it across all of its different components. Let's dive into how we can use it in our application.

First, we need to define our services. A service can be any kind of .NET class.

// Define a simple service public interface IMessageWriter { void Write(string message); } public class ConsoleMessageWriter : IMessageWriter { public void Write(string message) { Console.WriteLine(message); } }

An interface IMessageWriter has been defined, which represents a simple write operation, and a concrete implementation ConsoleMessageWriter that writes to the console.

Next, we need to register our services with DI container. This is usually done in ConfigureServices method in Startup.cs.

// Register the service with DI container public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMessageWriter, ConsoleMessageWriter>(); }

With this configuration, whenever an IMessageWriter instance is needed by any of the components, DI container will always provide an instance of ConsoleMessageWriter.

Finally, we are ready to use our service. Let's say we need it in one of our controllers.

public class HomeController : Controller { private IMessageWriter _messageWriter; public HomeController(IMessageWriter messageWriter) { _messageWriter = messageWriter; } public IActionResult Index() { _messageWriter.Write("This is dependency injection in action"); return View(); } }

After receiving the IMessageWriter instance in the constructor of the HomeController, we can use it whenever we need. The actual implementation is entirely handled by the DI container.

Conclusion

Dependency Injection promotes code reusability, testability and improves overall application maintainability. ASP.NET Core has built-in support for dependency injection, and it can be leveraged to design robust, maintainable applications.