Skip to content

6.11 — Third-Party Containers: Autofac and Scrutor

← Roadmap · Section: 6. Dependency Injection Prev: 6.10 Disposal · Next: 6.12 DI and testability

Markers: 🧠 · Confidence: 🔴 · Last reviewed: —


TL;DR

The built-in container is deliberately minimal. Two libraries fill the gaps.

  • Scrutor — not a container. It adds assembly scanning and decoration to the built-in one. Small, no lock-in.
  • Autofac — a full replacement container with property injection, interceptors and richer lifetimes.
  • The honest answer: most applications need neither. Reach for Scrutor first, and Autofac only for a specific missing feature.

Definitions

Term What it is What it means
Built-in container Microsoft.Extensions.DependencyInjection The default. Deliberately minimal — "good enough for 80% of apps".
Scrutor a NuGet package Extensions for the built-in container. Adds scanning and decoration. Not a replacement.
Autofac a NuGet package A full alternative container that plugs into ASP.NET Core.
Assembly scanning a technique Finding and registering types automatically by convention, rather than one line each.
Decoration a pattern Wrapping a registered service in another that adds behaviour. See 22.4.
Property injection an injection style Dependencies set via properties rather than the constructor. Not supported by the built-in container.
Interception a technique Automatically wrapping method calls — for logging, caching, retries — without writing a decorator.
IServiceProviderFactory<T> an interface The extension point a third-party container plugs into.
UseServiceProviderFactory a method How you tell the host to use a different container.

The concept

Why the built-in one is minimal on purpose

Microsoft designed Microsoft.Extensions.DependencyInjection to be the lowest common denominator. It supports what every container supports — constructor injection, three lifetimes, generics — and nothing more.

The reason is compatibility. If the framework relied on advanced features, every third-party container would have to implement them to be usable with ASP.NET Core. Keeping the abstraction small means any container can plug in.

The trade-off: it lacks several things mature containers have.

Feature Built-in Scrutor Autofac
Constructor injection ✅ ✅ ✅
Three lifetimes ✅ ✅ ✅
Open generics ✅ ✅ ✅
Keyed services ✅ (.NET 8+) ✅ ✅
Assembly scanning ❌ ✅ ✅
Decoration ❌ (manual) ✅ ✅
Property injection ❌ ❌ ✅
Interception ❌ ❌ ✅
Child lifetime scopes Limited — ✅

A picture: a hotel that provides a bed, a shower and a kettle. That covers most guests. If you need a kitchen, you book an apartment instead — but most people do not need one, and the apartment costs more.


How it works

The simple version — Scrutor

Scrutor is not a container. It adds extension methods to IServiceCollection, so you keep the built-in container entirely.

Assembly scanning — register by convention instead of one line per service:

// Instead of forty lines like this...
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<ICustomerService, CustomerService>();
// ...

// ...scan for them
builder.Services.Scan(scan => scan
    .FromAssemblyOf<OrderService>()
        .AddClasses(c => c.Where(t => t.Name.EndsWith("Service")))
        .AsImplementedInterfaces()
        .WithScopedLifetime());

That registers every class ending in "Service" against the interfaces it implements, as scoped.

⚠️ Scanning trades explicitness for brevity, and that trade is not free. With explicit registration you can search Program.cs for IOrderService and find where it is wired. With scanning, a service appears by convention, and the convention lives in a lambda somewhere. A typo in a class name silently means it is not registered, and the failure appears at runtime.

For a large codebase with a consistent convention it saves real effort. For a small one, explicit is clearer.

Decoration — the feature that genuinely fills a gap:

builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();

// Wrap it — consumers still inject IOrderRepository
builder.Services.Decorate<IOrderRepository, CachingOrderRepository>();
builder.Services.Decorate<IOrderRepository, LoggingOrderRepository>();

Compare with doing it by hand (6.8):

// The manual version — verbose, and easy to get wrong
builder.Services.AddScoped<EfOrderRepository>();
builder.Services.AddScoped<IOrderRepository>(sp =>
    new LoggingOrderRepository(
        new CachingOrderRepository(
            sp.GetRequiredService<EfOrderRepository>(),
            sp.GetRequiredService<IMemoryCache>()),
        sp.GetRequiredService<ILogger<LoggingOrderRepository>>()));

Scrutor handles the ordering and the resolution correctly. Decoration is the strongest reason to add it.

The decorator itself is an ordinary class:

public class CachingOrderRepository(
    IOrderRepository inner,                  // ← the wrapped one, injected
    IMemoryCache cache) : IOrderRepository
{
    public async Task<Order?> GetAsync(Guid id, CancellationToken ct)
    {
        if (cache.TryGetValue(id, out Order? cached))
            return cached;

        var order = await inner.GetAsync(id, ct);

        if (order is not null)
            cache.Set(id, order, TimeSpan.FromMinutes(5));

        return order;
    }
}

Note it takes IOrderRepository in its constructor — Scrutor supplies the previously registered implementation, not itself.

How it actually works — Autofac

Autofac replaces the container. You plug it in at the host level:

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

builder.Host.ConfigureContainer<ContainerBuilder>(container =>
{
    container.RegisterType<OrderService>().As<IOrderService>().InstancePerLifetimeScope();

    // Property injection — not possible with the built-in container
    container.RegisterType<ReportService>().PropertiesAutowired();

    // Interception — wrap every call without writing a decorator
    container.RegisterType<PaymentService>()
        .As<IPaymentService>()
        .EnableInterfaceInterceptors()
        .InterceptedBy(typeof(LoggingInterceptor));
});

builder.Services.Add... still works — Autofac reads those registrations too — so framework registrations like AddControllers() are unaffected.

The two features worth switching for:

Property injection, when you cannot change a constructor — usually because a base class in a framework you do not control defines it.

Interception, which applies cross-cutting behaviour to every method of an interface without writing a decorator per service. If you want logging or retries on twenty services, twenty decorators is a lot of code; one interceptor is not.

⚠️ Both come at a cost. Property injection hides dependencies, which is the same objection as service locator (6.9). Interception uses dynamic proxies, which are harder to debug — the stack trace goes through generated types — and do not work with Native AOT (3.2).

The deeper detail — should you?

The honest answer for most applications is no.

The built-in container covers constructor injection, three lifetimes, open generics and — since .NET 8 — keyed services. That is the large majority of what applications actually need.

Adding Scrutor is a small decision. It is a lightweight package that extends the existing container rather than replacing it, so there is no lock-in and no behaviour change to what you already have. If you need decoration, take it.

Replacing the container is a large decision:

  • Everyone on the team learns a second registration API
  • Debugging DI problems means understanding two systems
  • Some ASP.NET Core features assume the built-in container's behaviour
  • Container-specific registrations are hard to migrate away from later

⚠️ The question to ask: which specific feature do I need, and is there a simpler way? "More powerful" is not a reason. Needing interception across thirty services is.


Code

Decoration with Scrutor, which is the realistic case:

// The real implementation
builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();

// Layers applied inward-out: caching wraps EF, logging wraps caching
builder.Services.Decorate<IOrderRepository, CachingOrderRepository>();
builder.Services.Decorate<IOrderRepository, LoggingOrderRepository>();

// Resulting call order:
//   Logging → Caching → EfOrderRepository
public class LoggingOrderRepository(
    IOrderRepository inner,
    ILogger<LoggingOrderRepository> logger) : IOrderRepository
{
    public async Task<Order?> GetAsync(Guid id, CancellationToken ct)
    {
        var sw = Stopwatch.GetTimestamp();
        try
        {
            return await inner.GetAsync(id, ct);
        }
        finally
        {
            logger.LogDebug("GetAsync({Id}) took {Ms}ms",
                id, Stopwatch.GetElapsedTime(sw).TotalMilliseconds);
        }
    }
}

Neither EfOrderRepository nor any consumer knows the decorators exist. That is the value — you added caching and timing without touching either end.

⚠️ Decoration order is registration order, applied outermost-last. Registering logging before caching would put caching outside logging, so cache hits would not be logged. That is easy to get backwards.

Scanning, used carefully

builder.Services.Scan(scan => scan
    .FromAssemblyOf<OrderService>()

        // Everything ending in "Service" → its interfaces, scoped
        .AddClasses(c => c.Where(t => t.Name.EndsWith("Service")), publicOnly: true)
            .AsImplementedInterfaces()
            .WithScopedLifetime()

        // Everything implementing IValidator<> → all of them, scoped
        .AddClasses(c => c.AssignableTo(typeof(IValidator<>)))
            .AsImplementedInterfaces()
            .WithScopedLifetime());

That second block is where scanning genuinely shines — registering every validator without one line each, which pairs with IEnumerable<T> injection (6.7).


Interview questions

Q: Why would you replace the built-in DI container?

Usually you would not. The built-in one deliberately implements the lowest common denominator so that any third-party container can plug in, which means it covers constructor injection, the three lifetimes, open generics and keyed services — enough for most applications. You would replace it for a specific missing feature: property injection, when you cannot change a constructor because a framework base class defines it, or interception, when you want cross-cutting behaviour across many services without writing a decorator for each. "More powerful" is not a good enough reason, because you are asking the whole team to learn a second registration API and to debug two systems.

Q: What is Scrutor and how is it different from Autofac?

Scrutor is not a container at all — it is a small package of extension methods on IServiceCollection that adds two things the built-in container lacks: assembly scanning and decoration. You keep the built-in container entirely, so there is no lock-in and nothing about existing behaviour changes. Autofac is a full replacement container that plugs in through IServiceProviderFactory. So Scrutor is a small additive decision and Autofac is an architectural one.

Q: What is decoration and why does it need a library?

Decoration is wrapping a registered service in another implementing the same interface, so you can add caching or logging without changing the original or its consumers. The built-in container can do it, but only manually with factory registrations, and it is verbose and easy to get wrong — particularly the trap where registering the inner service as the interface makes the decorator wrap itself and recurse infinitely. Scrutor's Decorate handles the ordering and resolution correctly in one line, which is the strongest single reason to add it.

Q: What are the downsides of assembly scanning?

It trades explicitness for brevity. With explicit registration you can search for an interface and find exactly where it is wired; with scanning, services appear by convention and the convention is a lambda somewhere else. A class that does not match the naming pattern is silently not registered, and the failure appears at runtime rather than as a missing line you would notice in review. For a large codebase with a genuinely consistent convention it saves real effort, and for a smaller one explicit registration is clearer.


Traps ⚠️

  • Scanning hides registrations, so a class not matching the convention is silently unregistered.
  • Decoration order is registration order, applied outermost-last. Easy to get backwards.
  • A decorator resolving the interface it implements recurses infinitely, unless the library handles it.
  • Property injection hides dependencies, the same objection as service locator.
  • Interception uses dynamic proxies, which complicate stack traces and break Native AOT.
  • Replacing the container is hard to reverse. Container-specific registrations do not port.
  • Scanning by name is fragile. Renaming a class can silently unregister it.


Sources