The built-in .NET dependency injection container in depth: registration and resolution, service lifetimes and their failure modes, and advanced techniques such as keyed services, decorators, open generics and graph validation.
-
Your BackgroundService needs to read and update orders through the scoped AppDbContext and a scoped IOrderService. Show how you would write it correctly, explain why you can't inject them into the constructor, and cover cancellation, error handling and scope granularity.
Covers consuming scoped services from a singleton BackgroundService with IServiceScopeFactory.CreateAsyncScope per unit of work, including cancellation, per-item error handling, scope granularity and the .NET 8+ host behaviour on unhandled exceptions.
Mid-Level
Coding
Service Lifetimes
Β· π 3 follow-ups Β· π 1 real-world
-
What is the service locator anti-pattern? Why is injecting IServiceProvider and calling GetRequiredService inside your classes considered harmful, and where in an ASP.NET Core app is resolving from IServiceProvider acceptable?
Covers the service locator anti-pattern: hidden dependencies, runtime failures, testability and lifetime bugs, and the legitimate infrastructure uses of IServiceProvider such as composition roots, factories, middleware and workers.
Intermediate
Theory
Service Lifetimes
Β· π 3 follow-ups
-
Your ASP.NET Core service's memory grows steadily for days until the pod is OOM-killed, and a dotnet-gcdump shows thousands of instances retained through the DI container. Walk through how you diagnose DI-related memory growth (root-tracked transient disposables, long-lived scopes, captured singletons) and how you fix it.
Covers diagnosing memory growth caused by dependency injection: confirming managed growth with dotnet-counters, reading gcdump retention paths through ServiceProviderEngineScope, the three common DI causes, and fixes plus prevention.
Senior
Debugging
Service Lifetimes
Β· π 3 follow-ups Β· π 1 real-world
-
How do service lifetimes relate to thread safety? Explain what must be thread-safe in a singleton, why "A second operation was started on this context instance" happens even in scoped code, whether scoped services can be used from multiple threads in one request, and how per-request versus per-message scoping changes this.
Covers the concurrency contract each lifetime implies: thread-safe singletons, scoped services shared by parallel work within one request, DbContext concurrent use, and how message consumers and parallel processing need a scope per concurrent unit.
Senior
Theory
Service Lifetimes
Β· π 3 follow-ups Β· π 1 real-world
-
What does a DI scope mean outside an HTTP request? Explain how scopes work in message consumers, SignalR hubs, Blazor Server (and why scoped means per circuit there), Blazor WebAssembly, console apps and tests, and the bugs each one invites.
Covers who creates scopes and how long they last in message consumers, SignalR, Blazor Server circuits, Blazor WebAssembly, console apps and tests, with the typical bugs: long-lived DbContexts per circuit, missing scopes and root resolution.
Mid-Level
Theory
Service Lifetimes
Β· π 3 follow-ups Β· π 1 real-world
-
Code review: a Program.cs registers AppDbContext with AddSingleton, a TenantMiddleware takes the scoped ITenantContext in its constructor, a singleton ReportScheduler resolves a transient IDisposable exporter from an injected IServiceProvider on every run, and an HttpClient is registered as AddSingleton(new HttpClient()). What problems do you see, ranked by severity, and how would you fix them?
Covers reviewing DI registrations for lifetime defects: a singleton DbContext, a scoped service in a conventional middleware constructor, root-tracked transient disposables in a singleton, and a singleton HttpClient that never sees DNS changes, with the rewrite and review guard rails.
Senior
CodeReview
Service Lifetimes
Β· π 3 follow-ups Β· π 1 real-world
-
How would you decorate every IRepository<T> with a caching decorator using the built-in container only, without Scrutor?
Decorating an open generic service such as IRepository<T> in Microsoft.Extensions.DependencyInjection without Scrutor, by closing the types yourself, and the performance and AOT trade-offs.
Mid-Level
Theory
Advanced DI
-
How does the built-in .NET container handle open generic registrations such as AddScoped(typeof(IValidator<>), typeof(Validator<>))? Explain when the type gets closed, how a closed registration overrides the open one, what happens with generic constraints and IEnumerable<T>, and what you cannot do with open generics in Microsoft.Extensions.DependencyInjection.
How Microsoft.Extensions.DependencyInjection closes open generic registrations at resolution time, closed-over-open precedence, constraint handling, IEnumerable mixing, per-closed-type lifetimes and the limits (no factories, no partial closing, skipped by ValidateOnBuild).
Mid-Level
Theory
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
Show how you would use keyed services in .NET 10 to inject two differently configured implementations of the same interface, for example blob storage for invoices and for user uploads. Cover AddKeyedSingleton, [FromKeyedServices], IKeyedServiceProvider, [ServiceKey], KeyedService.AnyKey and what changed in .NET 10, and explain when a factory or strategy resolver is the better choice.
Keyed services in Microsoft.Extensions.DependencyInjection (.NET 8+, with .NET 10 changes): registering, injecting with [FromKeyedServices] in constructors and Minimal APIs, resolving through IKeyedServiceProvider, [ServiceKey], AnyKey fallbacks, and keyed services versus factories.
Mid-Level
Coding
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
Your app needs different implementations or settings depending on a name, the environment or configuration: two HttpClients for different partners, two sets of options for the same class, and a fake email sender in Development. How do you do named and conditional registration in .NET? Cover named and typed HttpClients, named options, registering by environment or configuration, and when the choice has to move to run time.
Named and conditional registration in .NET: named and typed HttpClients through IHttpClientFactory, named options with IOptionsMonitor.Get and IOptionsSnapshot.Get, registering implementations by environment or configuration in the composition root, and moving decisions to run time with feature flags or resolvers.
Intermediate
Theory
Advanced DI
Β· π 2 follow-ups
-
How do you register decorators with the .NET dependency injection container? Explain the manual factory approach with the built-in container, how decorators interact with lifetimes and disposal, decoration order, decorating open generics, and when you would use Scrutor's Decorate instead.
Registering decorators in Microsoft.Extensions.DependencyInjection: the manual inner-concrete-plus-factory approach, lifetime alignment and captive decorators, who disposes inner and outer objects, ordering of stacked decorators, open generic decoration and Scrutor's Decorate/TryDecorate.
Senior
Theory
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
Write a factory for objects that need both injected services and run-time arguments, for example a report exporter created per request with a format and a tenant id. Show a registered Func<string, T>, a typed factory interface, and ActivatorUtilities.CreateFactory, and explain who owns and disposes the objects the factory creates.
Building factories for objects that mix DI dependencies and run-time arguments: Func<string, T> registrations, typed factory interfaces, ActivatorUtilities.CreateInstance versus a cached ObjectFactory from CreateFactory, and the disposal and lifetime rules for objects the container does not track.
Intermediate
Coding
Advanced DI
Β· π 3 follow-ups
-
How do options work together with dependency injection? Explain IConfigureOptions<T>, IPostConfigureOptions<T> and the order they run in, how to configure options that depend on other services, which lifetimes those configure classes are resolved with, and why calling BuildServiceProvider to get a service inside Configure is wrong.
The options pipeline as a DI feature: IConfigureOptions, IConfigureNamedOptions, IPostConfigureOptions and IValidateOptions, their execution order in OptionsFactory, configuring options from other services with AddOptions<T>().Configure<TDep> or ConfigureOptions<T>, lifetime rules and the BuildServiceProvider anti-pattern.
Mid-Level
Theory
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
After a refactor, your API fails on the first request (or at start-up) with "A circular dependency was detected for the service of type 'OrderService'. OrderService -> InvoiceService -> OrderService." How do you find the cycle, why does it happen, and how do you break it properly? Why is injecting Lazy<T> or IServiceProvider to get around it a smell?
Diagnosing and fixing circular dependencies in Microsoft.Extensions.DependencyInjection: reading the call-site chain in the exception, why constructor injection can't satisfy a cycle, redesign options (extract a shared service, events, passing data as arguments, merging), and why Lazy<T> and service-locator workarounds hide the design problem.
Mid-Level
Debugging
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
What do ValidateScopes and ValidateOnBuild check in the .NET service provider? Explain the exact errors each one raises, why the host turns them on only in Development by default, whether you should turn them on everywhere, and what kinds of DI mistakes they still can't catch.
ServiceProviderOptions.ValidateScopes and ValidateOnBuild: what each validates and when (resolution versus build), the error messages, the Development-only default in the Generic Host, enabling them in tests or production with UseDefaultServiceProvider, their cost and their blind spots (factories, open generics, service locator calls, root-resolved transients).
Mid-Level
Theory
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
You are setting up DI for a large modular .NET 10 solution with ten feature modules and shared infrastructure. How do you organise the registrations? Discuss per-module extension methods, assembly scanning versus explicit registration, ordering and TryAdd for shared services, keeping implementations internal, start-up cost and Native AOT, and how you test the composition root.
Architecting DI registrations in a modular monolith or large solution: one AddXModule extension per module, internal implementations behind public registration methods, TryAdd for shared infrastructure, explicit versus scanned registration (Scrutor) and its start-up and AOT cost, and testing the composition root with validation and architecture tests.
Senior
Architecture
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world
-
What does dependency injection cost at run time in .NET, and how does Microsoft.Extensions.DependencyInjection behave under Native AOT and trimming? Explain how the container resolves services fast after the first call, where start-up cost comes from, which registration styles produce trimming warnings, what source-generated containers offer, and when any of this actually matters.
Performance and Native AOT for the built-in DI container: call-site caching, the switch from the reflection-based runtime resolver to compiled resolvers under JIT, the interpreter used under Native AOT, start-up costs (registration volume, scanning, ValidateOnBuild), trimming annotations and warnings, value-type generic limits, source-generated containers and when DI cost matters.
Senior
Theory
Advanced DI
Β· π 3 follow-ups Β· π 1 real-world