Dependency injection is a software design pattern that allows a class to receive its dependencies from external sources rather than creating them itself. This is useful in situations where a class is dependent on other classes and we want to decouple the class from the dependencies.
ASP.NET Core supports dependency injection out of the box. To use dependency injection in an ASP.NET Core application, follow these steps:
- Install the Microsoft.Extensions.DependencyInjection package:
Copy codeInstall-Package Microsoft.Extensions.DependencyInjection
- Create an interface and a class that implements the interface:
Copy codepublic interface IMailService
{
void Send(string to, string subject, string body);
}
public class MailService : IMailService
{
public void Send(string to, string subject, string body)
{
// Implementation of the Send method
}
}
- In the
Startup
class, add the interface and the class to the service container in theConfigureServices
method:
Copy codepublic void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMailService, MailService>();
}
- Inject the dependency into a controller using constructor injection:
Copy codepublic class HomeController : Controller
{
private readonly IMailService _mailService;
public HomeController(IMailService mailService)
{
_mailService = mailService;
}
public IActionResult Index()
{
_mailService.Send(\"user@example.com\", \"Hello\", \"Hello World!\");
return View();
}
}
By using dependency injection, we can easily swap out the implementation of the IMailService
interface with a different implementation, without changing the HomeController
class. This makes it easier to write unit tests and enables us to change the implementation of a class without modifying the consuming class.
In ASP.NET Core, the service container is responsible for creating and disposing of the dependencies. The service container can be configured to create dependencies as singleton, scoped, or transient. Singleton dependencies are created only once and are shared among all consumers. Scoped dependencies are created once per request. Transient dependencies are created every time they are requested.
Dependency injection is a powerful tool that can help you write more maintainable and testable code. It is an essential part of the ASP.NET Core framework and is used throughout the framework to enable loose coupling and modularity.
Leave a Reply