Defines inversion of control, dependency injection and the Dependency Inversion Principle, how they relate, why DI is used, and how the built-in ASP.NET Core container applies it.
Inversion of control (IoC) is the broad idea that something else controls the flow and object creation: the framework calls your code, not the other way round. Dependency injection (DI) is a specific IoC technique: a class declares what it needs, usually as constructor parameters, and a caller or container supplies it. The Dependency Inversion Principle (DIP) is the "D" in SOLID: high-level code depends on abstractions it owns, and low-level details implement them.
In ASP.NET Core you register services on builder.Services in Program.cs (the composition root), and the built-in container builds controllers, endpoints and middleware with their dependencies.
The trade-off: DI buys testability and replaceable parts at the cost of indirection; it is a tool, DIP is the design goal.
"They are three related ideas at different levels. Inversion of control is the broadest: instead of my code calling a library and driving everything, a framework drives and calls my code. ASP.NET Core is IoC: it owns the request loop and calls my endpoint. Dependency injection is one way of inverting control over object creation: a class doesn't
newup its collaborators, it declares them as constructor parameters and whoever builds it supplies them. The Dependency Inversion Principle is a design rule: high-level policy, like 'place an order', should depend on an abstraction such asIPaymentGatewaythat the policy owns, and the Stripe adapter should depend on that abstraction too.In .NET these meet in
Program.cs. I registerbuilder.Services.AddScoped<IPaymentGateway, StripeGateway>(), and when a request hitsOrderEndpoints, the container sees the endpoint needsOrderService, which needsIPaymentGateway, and builds the graph with the right lifetimes. That one place is the composition root, and it is the only place that knows about concrete types.The mistake I see is treating them as synonyms. You can use a DI container and still violate DIP, for example injecting
StripeGatewaydirectly or putting the interface in the infrastructure project. And you can follow DIP without a container by wiring things by hand inMain. DI is the mechanism; DIP is the reason the mechanism helps."
| Term | Kind | Question it answers | .NET example |
|---|---|---|---|
| Inversion of control | Broad principle | Who controls the flow and creation? | ASP.NET Core calls your endpoint; BackgroundService.ExecuteAsync is called by the host |
| Dependency injection | Technique | How does a class get its collaborators? | Constructor parameters filled by Microsoft.Extensions.DependencyInjection |
| Dependency Inversion Principle | Design rule (SOLID) | Which way should source dependencies point? | Orders.Application defines IPaymentGateway; Orders.Infrastructure implements it |
| Benefit | What it means in practice |
|---|---|
| Replaceable parts | Swap SmtpEmailSender for SendGridEmailSender in one line |
| Testability | Pass a fake IClock or IPaymentGateway in a unit test without touching the class |
| Lifetime management | The container decides singleton / scoped / transient and disposes services |
| Explicit dependencies | The constructor lists everything a class needs; hidden static calls disappear |
| Situation | Why |
|---|---|
Pure functions and value objects (Money, DateRange) |
No collaborators, nothing to inject |
| A 50-line console tool | Manual wiring in Main is clearer |
| Interfaces with exactly one implementation and no test seam needed | Inject the concrete class; add the interface when a second reason appears |
In a typical order API, the payment provider is behind IPaymentGateway. When the business moved from one provider to another, the change was a new adapter class plus one registration line in Program.cs; the 40 or so classes using the gateway did not change, and the integration tests swapped in a fake gateway so the suite still ran in under 2 minutes.
Checks whether the candidate can separate a principle, a technique and a design rule, and explain them with the ASP.NET Core container rather than buzzwords.
Green flags
Red flags
IServiceProvider inside business logicIn a classic library call your code is in control:
Your code ββcallsβββΆ Library
In a framework the arrow flips:
Framework (ASP.NET Core host) ββcallsβββΆ Your endpoint / middleware / BackgroundService
That flip is IoC. Events, callbacks, template methods and DI containers are all forms of it.
Without DI:
public class OrderService
{
private readonly StripeGateway _gateway = new(); // hard-wired, untestable
}
With DI the class only declares its needs; the caller provides them:
public class OrderService(IPaymentGateway gateway) { }
There are three classic forms: constructor injection (the default and best), property injection and method injection. The built-in .NET container supports constructor injection only; ASP.NET Core adds method-level injection for endpoint parameters and [FromServices].
Without DIP: Orders.Application βββΆ Orders.Infrastructure (StripeGateway)
With DIP: Orders.Application (owns IPaymentGateway)
β²
Orders.Infrastructure (StripeGateway : IPaymentGateway)
The high-level project no longer references the low-level one. The runtime call still flows from orders to Stripe; only the compile-time dependency is inverted.
Something must know every concrete type. In ASP.NET Core that is Program.cs (often split into AddOrders()-style extension methods). Rule: only the composition root resolves from the container; everything else just takes constructor parameters.
Program.cs ββregistersβββΆ IServiceCollection ββBuild()βββΆ IServiceProvider
β resolves per request
βΌ
Endpoint βββ OrderService βββ IPaymentGateway (StripeGateway)
builder.Services is a list of ServiceDescriptors (service type, implementation, lifetime). builder.Build() creates the root ServiceProvider. For each HTTP request ASP.NET Core creates a scope; scoped services live for that request and are disposed at its end.
OrderService that does new SmtpEmailSender() inside a method. Try to unit test it without sending email. Then refactor to constructor injection and pass a fake.Main. Notice that this is already DI.Microsoft.Extensions.DependencyInjection, register the same classes, call BuildServiceProvider() and resolve the top one. Compare.IPaymentGateway from the infrastructure project to the application project and check which project references which.A minimal ASP.NET Core app showing DIP (the abstraction lives with the policy) and DI (the container wires it).
// Orders.Application/IPaymentGateway.cs
namespace Orders.Application;
// The high-level layer owns the abstraction (DIP).
public interface IPaymentGateway
{
Task<PaymentResult> ChargeAsync(decimal amount, string currency, CancellationToken ct);
}
public sealed record PaymentResult(bool Succeeded, string Reference);
// Constructor injection: the service declares what it needs.
public sealed class OrderService(IPaymentGateway gateway)
{
public async Task<string> PlaceAsync(decimal total, CancellationToken ct)
{
var result = await gateway.ChargeAsync(total, "AUD", ct);
return result.Succeeded ? result.Reference : throw new InvalidOperationException("Payment declined");
}
}
// Orders.Infrastructure/FakeCardGateway.cs
namespace Orders.Infrastructure;
using Orders.Application;
// The low-level detail depends on the abstraction, not the other way round.
public sealed class FakeCardGateway : IPaymentGateway
{
public Task<PaymentResult> ChargeAsync(decimal amount, string currency, CancellationToken ct) =>
Task.FromResult(new PaymentResult(true, $"pay_{Guid.NewGuid():N}"));
}
// Program.cs: the composition root, the only place that knows concrete types.
using Orders.Application;
using Orders.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IPaymentGateway, FakeCardGateway>();
builder.Services.AddScoped<OrderService>();
var app = builder.Build();
// The endpoint parameter is injected by the framework (IoC + DI).
app.MapPost("/orders", async (decimal total, OrderService orders, CancellationToken ct) =>
TypedResults.Ok(await orders.PlaceAsync(total, ct)));
app.Run();
IServiceProvider and calling GetService inside business classes. Why it is wrong: that is the service locator, another form of IoC that is now considered an anti-pattern; dependencies become hidden and failures move to run time. Instead: list dependencies as constructor parameters.The senior framing is that DI is plumbing and DIP is architecture. A codebase can have a beautifully configured container and still have its domain layer referencing EF Core and HTTP clients directly. What I look for is where the abstractions live and whether the composition root is the only place that knows the concrete types.
The other senior signal is restraint: not every class needs an interface, and not every dependency needs injecting. DateTime.UtcNow is worth abstracting (use TimeProvider), Math.Round is not.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Built-in container + constructor injection | Any ASP.NET Core or Generic Host app | Low; already there | Rarely; only if you need features it lacks |
| Manual wiring ("pure DI") | Small tools, libraries' internals, teaching | Wiring code grows with the graph | Large apps with many scoped services |
| Static helpers / singletons by hand | Pure, stateless functions | Hidden coupling, hard to test | Anything with I/O, state or configuration |
DIP says high-level policy should not depend on low-level details; both should depend on abstractions, and the abstraction belongs to the high-level side. For example, the domain or application layer defines IPaymentGateway, and the infrastructure project implements it with Stripe; the arrow of source dependency points inwards. Dependency injection is a technique for supplying those implementations (constructor injection), and the .NET DI container is a tool that automates it. You can use a container without inverting anything (if interfaces live next to their implementations in infrastructure), and you can invert dependencies without a container.
A dependency is the weakest relationship: class A uses class B, so a change to B may affect A, but A does not keep B as part of its state. It shows up as a method parameter, a local variable, a return type, a static call or a new B() inside a method. Association is stronger: A stores a reference to B. Direction matters: high-level policy (business rules) should not depend on low-level details (SQL, HTTP). The Dependency Inversion Principle says both should depend on abstractions owned by the high-level side. Dependency injection supplies those abstractions from outside (usually through constructors), so classes do not create or find their own dependencies, which makes them testable and replaceable.
The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.
Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.
Last updated 23 Nov 2026.