Sobes.tech
Junior — Middle

Explain the concept of Dependency Injection in ASP.NET Core and how it is used in application development.

sobes.tech AI

Answer from AI

Dependency Injection (DI) in ASP.NET Core is a mechanism that allows dependencies (such as services, repositories) to be injected into classes without the need to create them manually. This enhances modularity, testability, and simplifies dependency management.

In ASP.NET Core, DI is built into the framework and configured in the ConfigureServices method of the Startup class or in Program.cs.

Example of registering and using a service:

// Service interface
public interface IMessageService {
    string GetMessage();
}

// Service implementation
public class MessageService : IMessageService {
    public string GetMessage() => "Hello from DI!";
}

// Registration in ConfigureServices
public void ConfigureServices(IServiceCollection services) {
    services.AddTransient<IMessageService, MessageService>();
}

// Usage via constructor
public class HomeController : Controller {
    private readonly IMessageService _messageService;
    public HomeController(IMessageService messageService) {
        _messageService = messageService;
    }

    public IActionResult Index() {
        var message = _messageService.GetMessage();
        return Content(message);
    }
}

Thus, ASP.NET Core will automatically create an instance of MessageService and pass it to the controller, eliminating the need to create objects manually.