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

📚 Interview question

When is the built-in Microsoft.Extensions.DependencyInjection container not enough? Compare it with Autofac, Lamar and Scrutor: what features does the built-in container deliberately leave out, and when would you bring in another container or library?

Compares the built-in .NET container with Autofac, Lamar and Scrutor: missing features (property injection, scanning, decorators, child containers, implicit Func/Lazy), how third-party containers plug in with UseServiceProviderFactory, and when switching is justified.

Intermediate Theory Intermediate aspnet-core autofac dependency-injection lamar scrutor

🎯 Key points

  • Built-in container is a conforming minimum: constructor injection, three lifetimes, open generics, IEnumerable, keyed services (.NET 8+)
  • Missing: property injection, assembly scanning, decorators, interception, child/tagged scopes, implicit Func/Lazy/Owned
  • Scrutor is not a container: it adds Scan() and Decorate() on top of IServiceCollection
  • Autofac and Lamar replace the provider via UseServiceProviderFactory / UseLamar
  • Third-party containers must pass the Microsoft.Extensions.DependencyInjection specification tests
  • Cost of switching: another dependency, slower start-up or AOT issues, team learning curve
  • Prefer built-in plus Scrutor or source generators unless you need advanced features

⏱ 30-second answer

The built-in container is deliberately a minimum: constructor injection, singleton/scoped/transient, open generics, IEnumerable<T> and, since .NET 8, keyed services. It leaves out property injection, assembly scanning, decorators, interception, child or tagged scopes and implicit Func<T>/Lazy<T>.

  • Scrutor isn't a container; it adds Scan() and Decorate() extension methods to IServiceCollection.
  • Autofac and Lamar replace the provider through UseServiceProviderFactory and add modules, decorators, interception and richer scopes.

My default is built-in plus Scrutor if needed. The trade-off: a full container adds power but also a dependency, start-up cost and a learning curve for every new developer.

🗣 Full answer (senior)

How I would answer this in an interview

"The built-in container is designed as the lowest common denominator that every library and every third-party container can agree on. It does constructor injection, the three lifetimes, open generics, IEnumerable<T> for multiple registrations, and keyed services since .NET 8. What it deliberately doesn't do is property injection, convention-based assembly scanning, decorators, interception or AOP, child containers and tagged lifetime scopes, and the implicit relationship types Autofac has, like Func<T>, Lazy<T> and Owned<T>.

For most services that's fine. When I hit a gap, I go up in small steps. If I just want scanning or decorators, Scrutor gives me services.Scan(...) and services.Decorate<IRepo, CachingRepo>() while staying on the built-in provider. If I need things like interception with Castle DynamicProxy, per-tenant child scopes or modules shared with an older codebase, I'd consider Autofac, which plugs in with builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()). Lamar is StructureMap's successor and plugs in similarly; I'd mainly see it in codebases migrating from StructureMap.

The mistake I see is teams adding Autofac on day one out of habit and then using none of its features, while paying for slower start-up, a harder Native AOT story and an extra thing to upgrade. The question I ask is 'which feature do we need that the built-in container can't do in ten lines?' If there isn't one, we stay built-in."


Feature comparison

Feature Built-in Scrutor (on built-in) Autofac Lamar
Constructor injection, 3 lifetimes Yes Yes Yes Yes
Open generics, IEnumerable<T> Yes Yes Yes Yes
Keyed / named services Yes (.NET 8+) Yes Yes Yes
Assembly scanning No Yes (Scan) Yes Yes
Decorators Manual factory Yes (Decorate) Yes Yes
Property injection No No Yes Yes (setter policies)
Interception / AOP No No Yes (DynamicProxy) Limited
Child / tagged scopes No No Yes Nested containers
Implicit Func<T>, Lazy<T> No No Yes Yes
Native AOT friendly Yes Scanning is reflection-heavy Reflection-heavy Reflection and codegen

When to move beyond built-in

Need Lightest option
Register 200 handlers by convention Scrutor Scan, or a source generator
Decorate a repository with caching Scrutor Decorate or a manual factory
Per-tenant configuration with child scopes Autofac (or redesign with keyed services/options)
Method interception for auditing Autofac + DynamicProxy, or source-generated decorators
Migrating a StructureMap app Lamar

Production example

A service with about 300 MediatR-style handlers originally used Autofac only for assembly scanning. Replacing it with Scrutor's Scan kept the same registrations, removed one dependency and cut cold start by around 150 ms, which mattered for a scale-to-zero Container App.

🔍 What the interviewer is checking

Checks the candidate knows what the built-in container provides and lacks, and makes a cost-aware decision about third-party containers.

Green flags

  • Lists concrete missing features (scanning, decorators, property injection, child scopes)
  • Knows Scrutor sits on top of the built-in provider
  • Knows how Autofac plugs in with UseServiceProviderFactory
  • Weighs start-up and Native AOT costs

Red flags

  • "Always use Autofac" with no reason
  • Can't name what the built-in container lacks
  • Unaware that keyed services now exist in the built-in container

📚 Learn in depth

1. The conforming container contract

ASP.NET Core resolves everything through IServiceProvider. Third-party containers integrate by implementing IServiceProviderFactory<TContainerBuilder>:

IServiceCollection (framework + your registrations)
        │  CreateBuilder(services)
        ▼
Autofac ContainerBuilder  ← ConfigureContainer<ContainerBuilder>(b => ...)
        │  CreateServiceProvider(builder)
        ▼
AutofacServiceProvider : IServiceProvider, IKeyedServiceProvider ...

Microsoft publishes the Microsoft.Extensions.DependencyInjection.Specification.Tests package describing the behaviour the framework relies on: last registration wins, IEnumerable<T> order, scoped disposal, keyed-service semantics and so on. Nothing forces a container to run them, but mainstream adapters (Autofac, Lamar and others) do, and a container that fails them can break ASP.NET Core in subtle ways. That's why the built-in feature set is effectively the contract.

2. What Scrutor actually does

Scrutor only manipulates IServiceCollection:

  • Scan reflects over assemblies at start-up and adds ServiceDescriptors by convention.
  • Decorate<TService, TDecorator> finds existing descriptors for TService and replaces each with a factory descriptor that builds the original and wraps it.

The provider is still the built-in one, so runtime behaviour and performance stay the same.

3. Autofac extras worth knowing

  • Modules group registrations.
  • Lifetime scopes with tags (InstancePerMatchingLifetimeScope) model units of work beyond HTTP requests.
  • Owned<T> gives the consumer its own disposable scope for the dependency.
  • Interception via Castle DynamicProxy.

4. Costs

  • Start-up: scanning and container building can add tens to hundreds of milliseconds, which matters for scale-to-zero hosts.
  • Native AOT and trimming: the trimmer keeps only types it can see statically referenced. Types discovered by reflection-based scanning, or created through dynamic proxies, may be removed or need dynamic code that AOT can't provide, so you get trim warnings at publish and missing-type failures at run time.
  • Two registration languages in one codebase confuse people.

Try it yourself

  1. Register 50 handlers manually, then with Scrutor's Scan; measure start-up with a Stopwatch around builder.Build().
  2. Add a caching decorator with Scrutor's Decorate and check the resolved type chain in a test.
  3. Plug Autofac into a sample app with UseServiceProviderFactory and register a module.
  4. Publish a sample with PublishAot=true using Scrutor scanning and read the trim warnings.

💻 Code

Staying on the built-in provider with Scrutor, and plugging in Autofac when you really need it.

// Option 1: built-in provider + Scrutor for scanning and decoration.
var builder = WebApplication.CreateBuilder(args);

builder.Services.Scan(scan => scan
    .FromAssemblyOf<Program>()
    .AddClasses(c => c.AssignableTo(typeof(ICommandHandler<>)))
    .AsImplementedInterfaces()
    .WithScopedLifetime());

builder.Services.AddScoped<IProductRepository, SqlProductRepository>();
builder.Services.Decorate<IProductRepository, CachingProductRepository>();

var app = builder.Build();
app.Run();

public interface ICommandHandler<in TCommand> { Task HandleAsync(TCommand command, CancellationToken ct); }
public interface IProductRepository { Task<string?> FindAsync(int id, CancellationToken ct); }
public sealed class SqlProductRepository : IProductRepository
{
    public Task<string?> FindAsync(int id, CancellationToken ct) => Task.FromResult<string?>($"product {id}");
}
public sealed class CachingProductRepository(IProductRepository inner) : IProductRepository
{
    public Task<string?> FindAsync(int id, CancellationToken ct) => inner.FindAsync(id, ct); // cache here
}
// Option 2: replace the provider with Autofac (only when you need its features).
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(container =>
{
    container.RegisterModule<BillingModule>();
});

⚠ Common mistakes

  • Mistake: Adding Autofac by default "because the built-in container is too basic". Why it is wrong: most apps use none of the extra features and pay in start-up, AOT compatibility and onboarding. Instead: name the missing feature first.
  • Mistake: Calling Scrutor a container. Why it is wrong: it only adds descriptors to IServiceCollection; the built-in provider still resolves. Instead: describe it as registration helpers.
  • Mistake: Mixing registrations between IServiceCollection and ConfigureContainer without knowing the order. Why it is wrong: container-specific registrations run after and can silently override. Instead: keep one style per service and document it.
  • Mistake: Assuming everything works the same after switching containers. Why it is wrong: subtle differences (disposal order, constructor selection, property injection) change behaviour. Instead: run integration tests and the composition-root test after switching.
  • Mistake: Using assembly scanning in a Native AOT app. Why it is wrong: types found by reflection may be trimmed away. Instead: register explicitly or use a source generator.
  • Mistake: Using interception for business logic. Why it is wrong: behaviour becomes invisible in the code. Instead: keep interception for cross-cutting concerns, or prefer explicit decorators.

🏛 Senior insight: trade-offs

The senior answer is a ladder, not a choice between two products: built-in first, then registration helpers (Scrutor or a source generator), then a full container only for a feature you can name. Each step adds a dependency, start-up cost and something new developers must learn, and full containers make Native AOT and trimming harder because they rely on reflection, scanning and dynamic proxies.

Measure before and after: time builder.Build() and the first request, check trim warnings with PublishAot=true if AOT is on the roadmap, and run the integration suite, because containers differ subtly in disposal order and constructor selection.

Option When it fits Cost When not to
Built-in only Most APIs and workers None You need interception or tagged scopes
Built-in + Scrutor Convention scanning, decorators Reflection at start-up; AOT-unfriendly scanning Native AOT apps (register explicitly instead)
Autofac Interception, Owned<T>, tagged lifetime scopes, existing modules Extra dependency, slower build, two registration styles Greenfield apps with no named need
Lamar Migrating from StructureMap Smaller community; codegen at start-up New projects without StructureMap history

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Scrutor's Decorate Why: Checks hands-on decorator registration and its pitfalls
    How to answer

    The decorator implements IProductRepository and reads through HybridCache.GetOrCreateAsync, sending misses to the inner repository. HybridCache gives an in-memory L1 cache, an optional distributed L2, and stampede protection: 500 concurrent misses for a key make one database call.

    • Keys include everything that changes the result: product:v1:{tenant}:{id}.
    • Writes go through the decorator and invalidate after the inner write succeeds.
    • Exceptions aren't cached. Caching null is a deliberate choice with a short TTL.

    Register it with a factory delegate or a keyed inner service, or use Scrutor's Decorate<,>(). The trade-off is staleness: choose the TTL from how stale the business can tolerate.

  2. When: Candidate mentions open generics Why: Checks open generic registration and the built-in container's limits
    How to answer

    You register the open types, services.AddScoped(typeof(IRepository<>), typeof(Repository<>)), and when someone asks for IRepository<Order> the container closes the implementation with MakeGenericType and builds it, caching that plan. An exact closed registration for IRepository<Order> wins over the open one, while IEnumerable<IRepository<Order>> returns both. Lifetimes are per closed type. Microsoft DI has no decorator support, so I use Scrutor's Decorate for open generics or write it by hand. ValidateOnBuild cannot check open generics, so I add tests that resolve real closed types.

  3. When: Candidate talks about registration order or overrides Why: Checks last-wins, TryAdd and IEnumerable<T> semantics
    How to answer

    IServiceCollection is just a list of ServiceDescriptors: a service type, an implementation (type, instance or factory delegate) and a lifetime. AddSingleton, AddScoped and AddTransient append to that list.

    • If you register the same service type several times, injecting T gives you the last registration, while injecting IEnumerable<T> gives you all of them in registration order.
    • TryAdd* adds only if nothing is registered for that service type, which is how libraries provide overridable defaults. TryAddEnumerable adds only if that exact implementation isn't already there.
    • Replace swaps the first registration; RemoveAll clears them.

    The trade-off: ordering makes overrides easy but silent, so registration order bugs are easy to write and hard to see.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me