Dependency injection in ASP.NET Core

Posted by

Dependency Injection (DI) is a design pattern that helps in creating loosely coupled applications. It allows developers to write clean, maintainable, and testable code.

Here is a step-by-step tutorial on how to implement Dependency Injection in ASP.NET Core.

  1. Create an ASP.NET Core web application:
dotnet new webapp -n MyWebApp
  1. Install the Microsoft.Extensions.DependencyInjection NuGet package:
dotnet add package Microsoft.Extensions.DependencyInjection
  1. Create an interface and a class that implements the interface. This is the class that we want to inject as a dependency. For example:
public interface IService
{
    string GetMessage();
}

public class Service : IService
{
    public string GetMessage()
    {
        return "Hello from Service";
    }
}
  1. In the Startup.cs file, add the following code in the ConfigureServices method to configure the dependency injection container:
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IService, Service>();
}
  1. Inject the dependency in a controller or any other class that needs it. For example, in the HomeController.cs file, add the following code:
public class HomeController : Controller
{
    private readonly IService _service;

    public HomeController(IService service)
    {
        _service = service;
    }

    public IActionResult Index()
    {
        ViewData["Message"] = _service.GetMessage();
        return View();
    }
}
  1. Finally, run the application and access the home page to see the message from the Service class.

That’s it! This is a basic example of Dependency Injection in ASP.NET Core. In a real-world scenario, you may have multiple dependencies, and you can add them to the dependency injection container in the same way.

Note: The AddTransient method creates a new instance of the Service class each time it is requested. There are also other methods available like AddSingleton and AddScoped to control the lifetime of the dependencies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.