📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the difference between inversion of control, dependency injection and the Dependency Inversion Principle? Why do we use DI at all, and what does it look like in an ASP.NET Core app?

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.

Beginner Theory Beginner aspnet-core dependency-injection dependency-inversion inversion-of-control solid

🎯 Key points

  • IoC = the framework calls your code and controls object creation (Hollywood principle); events, callbacks, template methods and containers are all forms of it
  • DI = a class receives its dependencies through its constructor instead of creating them with new
  • DIP = high-level modules must not depend on low-level modules; both depend on abstractions, and the abstraction is owned by the high-level layer
  • DI is one way to achieve IoC; the service locator is another, and it is an anti-pattern
  • The composition root (Program.cs) is the one place that wires implementations to abstractions
  • builder.Services registers, the container resolves, constructor injection is the default in ASP.NET Core
  • Benefits: swap implementations, test with fakes, central lifetime management; little value for pure functions and value objects
  • DI without DIP still couples you to concretions; DIP without DI is possible with manual wiring

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 new up 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 as IPaymentGateway that the policy owns, and the Stripe adapter should depend on that abstraction too.

In .NET these meet in Program.cs. I register builder.Services.AddScoped<IPaymentGateway, StripeGateway>(), and when a request hits OrderEndpoints, the container sees the endpoint needs OrderService, which needs IPaymentGateway, 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 StripeGateway directly or putting the interface in the infrastructure project. And you can follow DIP without a container by wiring things by hand in Main. DI is the mechanism; DIP is the reason the mechanism helps."


The three terms side by side

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

Why use DI

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

When DI is not worth it

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

Production example

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.

πŸ” What the interviewer is checking

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

  • Gives one-line definitions of all three and how they relate
  • Mentions the composition root and constructor injection
  • Says where the abstraction should live (with the consumer)
  • Knows DI works without a container

Red flags

  • "DI and DIP are the same thing"
  • Thinks DI means "use interfaces everywhere"
  • Resolves services from IServiceProvider inside business logic

πŸ“š Learn in depth

1. Inversion of control: who is in charge

In 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.

2. Dependency injection: creation is inverted

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].

3. Dependency Inversion: the arrow in your source code

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.

4. The composition root

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)

5. What the container actually does

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.

Try it yourself

  1. Write 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.
  2. Create a console app with no container and wire three classes by hand in Main. Notice that this is already DI.
  3. Add Microsoft.Extensions.DependencyInjection, register the same classes, call BuildServiceProvider() and resolve the top one. Compare.
  4. Move IPaymentGateway from the infrastructure project to the application project and check which project references which.

πŸ’» Code

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();

⚠ Common mistakes

  • Mistake: Using IoC, DI and DIP as synonyms. Why it is wrong: they are a principle, a technique and a design rule; interviewers use the question to see if you know the difference. Instead: define each in one line and show how DI is one way to achieve IoC and helps apply DIP.
  • Mistake: Thinking a DI container is required for DI. Why it is wrong: passing dependencies through constructors by hand is already DI. Instead: treat the container as automation for wiring and lifetimes.
  • Mistake: Putting the interface in the infrastructure project next to its implementation. Why it is wrong: the high-level project must then reference infrastructure, so the dependency is not inverted. Instead: let the consuming layer own the abstraction.
  • Mistake: Injecting 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.
  • Mistake: Creating an interface for every class "for DI". Why it is wrong: the container can inject concrete classes; single-implementation interfaces add noise and indirection. Instead: add an interface when at least one of these is true: there is (or will soon be) a second implementation; the dependency does I/O or touches time, randomness or an external system you need to fake in tests; or the abstraction marks a layer boundary under DIP (the domain must not reference infrastructure). Otherwise inject the concrete class.
  • Mistake: Newing up collaborators inside a class that is otherwise injected. Why it is wrong: those collaborators can't be replaced or tested and bypass lifetime management. Instead: inject them, or inject a factory (Factory pattern) if they need run-time data.

πŸ› Senior insight: trade-offs

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

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions the Dependency Inversion Principle or layered architecture Why: Checks the candidate can apply DIP across projects, not just define it
    How to answer

    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.

  2. When: Candidate talks about coupling between classes Why: Checks understanding of dependency versus association and why direction matters
    How to answer

    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.

  3. When: Candidate mentions Program.cs or wiring services together Why: Checks the candidate knows where container knowledge should stop
    How to answer

    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.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me