C# › Dependency Injection & IoC Principles

How do you register and resolve a service using ASP.NET Core's built-in dependency injection container?

Beginner

Answer

Register a service's interface-to-implementation mapping in Program.cs using builder.Services.AddXxx(), then ASP.NET Core automatically INJECTS it into any controller or class constructor that declares a dependency on that interface — you never call 'new' or manually resolve it yourself.
// Program.cs
builder.Services.AddScoped<IOrderService, OrderService>();

// Automatically injected into a controller's constructor
public class OrdersController : ControllerBase {
  private readonly IOrderService _orderService;
  public OrdersController(IOrderService orderService) { _orderService = orderService; }
}
Real-world example Registering a repository or service interface in an ASP.NET Core web API's startup configuration.

Common follow-ups: What happens if you inject a service into a constructor but forget to register it in the DI container?