Advertisement

Dependency Injection interview questions and answers

15 Dependency Injection interview questions for ASP.NET Core roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How would you unit test a service or minimal API handler that depends on multiple injected interfaces, without spinning up the full DI container?

Unit tests typically construct the class or call the handler function directly, passing mock or fake implementations of its dependencies (created via a mocking library like Moq or NSubstitute) directly as constructor or parameter arguments -- bypassing the DI container entirely, since unit tests should test the logic in isolation, reserving the real DI container's wiring behavior for integration tests using WebApplicationFactory.
[Fact]
public async Task ProcessOrder_SendsConfirmationEmail() {
    var mockEmailSender = new Mock<IEmailSender>();
    var sut = new OrderService(mockEmailSender.Object);  // direct construction, no DI container

    await sut.ProcessOrderAsync(new Order());

    mockEmailSender.Verify(e => e.SendAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
Real-world example
A test suite for OrderService directly constructs it with a mocked IEmailSender, verifying business logic behavior in milliseconds without any DI container overhead or network/database dependencies.
Likely follow-ups
  • When would an integration test actually need to resolve services through the real DI container?
  • How do you test a minimal API handler function that takes many injected parameters?
Testing ASP.NET Core Applications Controllers vs Minimal APIs
Q12 Intermediate Save

How does the Options pattern's IOptions<T>/IOptionsSnapshot<T> relate to and build upon the standard DI container?

IOptions<T>, IOptionsSnapshot<T>, and IOptionsMonitor<T> are themselves services resolved through the DI container (registered implicitly when you call Configure<T>()), demonstrating that the Options pattern is built entirely on top of standard DI infrastructure rather than being a separate mechanism -- IOptions<T> is registered as Singleton internally, IOptionsSnapshot<T> as Scoped, explaining their respective behavior around configuration change visibility and captive dependency risk.
// Configure<T> implicitly registers the necessary IOptions<T> infrastructure
builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("Smtp"));

// Under the hood, this makes IOptions<SmtpSettings>, IOptionsSnapshot<SmtpSettings>,
// and IOptionsMonitor<SmtpSettings> all resolvable via the same DI container
Real-world example
Understanding that IOptionsSnapshot<T> is registered as Scoped explains precisely why it can't be safely injected into a Singleton service -- it's the exact same captive dependency problem as any other Scoped service being consumed by a Singleton.
Likely follow-ups
  • Why does IOptionsMonitor<T> avoid the captive dependency problem despite being usable in Singletons?
  • How would you build a custom pattern following these same DI principles?
Configuration & Options Pattern Background Tasks & Hosted Services
Q13 Advanced Save

How do third-party DI containers like Autofac integrate with ASP.NET Core's built-in DI abstractions, and why would a team choose one?

ASP.NET Core's DI system is built around abstractions (IServiceCollection for registration, IServiceProvider for resolution) that third-party containers can replace entirely via a custom IServiceProviderFactory, letting you still register services using the built-in IServiceCollection (for compatibility with framework registrations) while gaining advanced features the built-in container lacks -- multiple constructor resolution, property injection, or convention-based module/assembly scanning -- Autofac being the most common choice for teams needing these capabilities.
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder => {
    containerBuilder.RegisterModule<MyAutofacModule>();
});
Real-world example
A large enterprise application with complex conditional registration requirements (convention-based module discovery across many assemblies) adopts Autofac specifically for its more powerful registration API, while still leveraging built-in framework services registered via standard IServiceCollection calls.
Likely follow-ups
  • What features does Autofac provide that the built-in container lacks?
  • What's the performance trade-off of using a more feature-rich third-party container?
Dependency Injection .NET CLI SDK & Project Structure (csproj)
Q14 Intermediate Save

What does GetService<T>() return compared to GetRequiredService<T>() when a service isn't registered, and which should application code generally prefer?

GetService<T>() returns null if the requested service type isn't registered, requiring the caller to handle the null case explicitly. GetRequiredService<T>() instead throws an InvalidOperationException immediately with a clear message identifying the missing service, generally preferred in application code since a missing required dependency usually indicates a configuration bug that should fail loudly and immediately rather than propagate a confusing null reference later.
var logger = serviceProvider.GetService<ILogger<MyClass>>();  // returns null if not registered
if (logger is null) { /* handle missing case explicitly */ }

var requiredLogger = serviceProvider.GetRequiredService<ILogger<MyClass>>();  // throws clearly if missing
Real-world example
A team standardizes on GetRequiredService throughout their startup code specifically so a missing service registration causes an immediate, clear startup failure instead of a null reference exception deep inside unrelated business logic hours later.
Likely follow-ups
  • When is GetService's null-returning behavior actually useful over GetRequiredService?
  • How does constructor injection avoid needing either of these calls directly?
Diagnostics & Performance Global Exception Handling & Middleware
Q15 Advanced Save

How does ValidateOnBuild help catch dependency injection configuration errors immediately at application startup rather than at runtime?

When ValidateOnBuild is enabled (on by default in Development via the default host builder), calling builder.Build() eagerly validates that every registered service's dependencies can actually be resolved, throwing an immediate, clear exception at startup for missing registrations rather than a confusing failure later when a specific code path first tries to resolve that broken service -- combined with ValidateScopes (also on by default in Development), it also catches captive dependency issues at the same point.
var builder = WebApplication.CreateBuilder(args);
// In Development, ValidateOnBuild and ValidateScopes run automatically at Build() time,
// catching missing registrations and captive dependencies immediately

var app = builder.Build();  // throws here if misconfigured, not later at runtime
Real-world example
A missing service registration that would have caused a runtime crash only when a specific rarely-hit code path executed is instead caught immediately at application startup during local development, thanks to ValidateOnBuild eagerly checking the entire dependency graph.
Likely follow-ups
  • Why are these validations typically disabled in Production for performance reasons?
  • How do you explicitly enable them in Production if you want the extra safety despite the cost?
Diagnostics & Performance Testing ASP.NET Core Applications

Showing 11–15 of 15