Skip to content
Sharp

Dependency injection · interview question

Why use dependency injection? Explain constructor injection and the benefits it brings to an ASP.NET Core app.

Interview answerMedium

0 words · aim for 40+

Answer and explanation

Correct answer

Dependency injection means a class receives its dependencies from outside instead of creating them. With constructor injection the dependencies are constructor parameters, usually interfaces, for example OrderService(IOrderRepository repo, ILogger<OrderService> log). The container builds the object graph from registrations like builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>().

Benefits: loose coupling (code depends on abstractions), easy unit testing (pass fakes or mocks), central control of lifetimes (transient, scoped, singleton) and disposal, swapping implementations through configuration, and explicit dependencies that are visible in the constructor.

Key points:
- Dependencies are provided from outside rather than created with new
- Constructor injection: dependencies are constructor parameters, typically interfaces
- Services are registered in the container with a lifetime
- Improves testability: you can inject fakes or mocks
- Loose coupling: implementations can be swapped

Why

Good answers connect DI to testability and lifetimes, not just "the framework does it".

Test yourself on Dependency injection

A free test with instant, explained results. No account needed.

Start free test