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.
- Create an ASP.NET Core web application:
dotnet new webapp -n MyWebApp
- Install the Microsoft.Extensions.DependencyInjection NuGet package:
dotnet add package Microsoft.Extensions.DependencyInjection
- 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";
}
}
- 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>();
}
- 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();
}
}
- 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.