skip to content

Scanning & Third-Party Containers

Scrutor adds assembly scanning and decorators to the built-in container, and IServiceProviderFactory swaps in a full container. Interviewers ask what the default lacks and when replacing it pays off.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

4

In ASP.NET Core 10, how do you replace the built-in container through IServiceProviderFactory, and what do you lose or gain by doing it?

level: seniorimportance: must knowfreq 45%

answer

  1. CreateBuilder, then CreateServiceProvider
  2. builder.Host.UseServiceProviderFactory(...)
  3. ConfigureContainer<TContainerBuilder> runs at Build()
  4. Development scope validation stays behind
  5. keyed services since .NET 8 narrowed the gap

basics

~10 s

Pass an IServiceProviderFactory<TContainerBuilder> to builder.Host.UseServiceProviderFactory and add container-specific registrations in builder.Host.ConfigureContainer<TContainerBuilder>. You gain the container's extra features but lose the default factory's Development scope validation.

solid answer

~40 s

`IServiceProviderFactory<TContainerBuilder>` has two methods: `CreateBuilder(IServiceCollection)` copies every registration into the other container's builder, and `CreateServiceProvider(TContainerBuilder)` builds it and returns an `IServiceProvider`. In ASP.NET Core 10 you plug one in with `builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())` and register container-specific things in `builder.Host.ConfigureContainer<ContainerBuilder>(...)`. Those callbacks run at `builder.Build()`, after all `builder.Services` registrations. The type argument must match the factory's builder type, or `Build()` fails with an `InvalidCastException`. The trade-off: you gain features the built-in container lacks, such as property injection, child containers per tenant and modules, but the Development-only `ValidateScopes` and `ValidateOnBuild` belong to `DefaultServiceProviderFactory` and no longer apply. Since .NET 8, keyed services and Scrutor's scanning and decoration cover many of the old reasons to switch.

code

csharp · 11 lines
csharp
using Autofac;
using Autofac.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IRouteQueries, RouteQueries>();

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(container =>
    container.RegisterModule(new TenantRoutingModule()));

var app = builder.Build(); // CreateBuilder, callbacks, CreateServiceProvider

go deeper

for a junior

Recall that ASP.NET Core can use another container through UseServiceProviderFactory, and that ordinary builder.Services registrations keep working.

for a middle

Explain CreateBuilder and CreateServiceProvider, when ConfigureContainer callbacks run, and why the builder type argument must match the factory.

for a senior

Weigh the lost Development scope validation and the different lifetime rules against concrete needs like per-tenant child scopes, and say which old reasons keyed services and Scrutor removed.

for a principal

Own the decision record for a container replacement across a portfolio: which requirement justifies it, how it is tested, and when to revisit it at an LTS upgrade.

## The seam: IServiceProviderFactory<TContainerBuilder> ASP.NET Core never resolves services through a specific container class. It needs an `IServiceProvider`, and it obtains one from an **`IServiceProviderFactory<TContainerBuilder>`**: | Member | Job | |---|---| | `TContainerBuilder CreateBuilder(IServiceCollection services)` | turn the collected registrations into the other container's builder | | `IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder)` | build that container and expose it as `IServiceProvider` | The default is `DefaultServiceProviderFactory`, whose builder type is `IServiceCollection` itself. `WebApplicationBuilder` creates it with `ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }` in Development and with no validation elsewhere. ## Plugging another container in With `WebApplicationBuilder`, the hooks are on `builder.Host`: ```csharp builder.Services.AddScoped<IRouteQueries, RouteQueries>(); // still works builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(container => container.RegisterModule(new TenantRoutingModule())); var app = builder.Build(); ``` What happens at `builder.Build()`: 1. The factory's `CreateBuilder` copies every `builder.Services` descriptor, so framework services and your own `AddScoped` calls keep working. 2. The `ConfigureContainer<ContainerBuilder>` callbacks run with that builder. They run **after** all `builder.Services` registrations, whatever order the lines appear in. 3. `CreateServiceProvider` builds the container, and the app resolves everything through it, including controllers, middleware and handlers. Details that trip people up: - The type argument of `ConfigureContainer<T>` must be the factory's builder type. A mismatch is not caught at compile time; `Build()` throws `InvalidCastException`. - `WebApplicationBuilder` also implements `IHostApplicationBuilder.ConfigureContainer(factory, configure)`, explicitly, so it is reachable only through a cast to that interface. `builder.Host` is the usual route. - In Autofac's integration package, `services.AddAutofac()` only registers the factory as a service. Its own documentation says it works only with pre-3.0 hosting, not the generic host behind `WebApplication`. The README's mention of a `UseAutofac` call also does not match the package, which has no such method. Use `UseServiceProviderFactory`. ## What you lose - **Development validation.** `ValidateScopes` and `ValidateOnBuild` are options of the built-in provider. With another factory they do not apply; whatever checks the other container performs replace them, and you must learn what those are. - **The single mental model.** Autofac's `AutofacServiceProvider` implements `IServiceProvider` and, for keyed services, `IKeyedServiceProvider`, but Autofac's own lifetimes, defaults and disposal rules apply to registrations made through its `ContainerBuilder`, so the team now has two sets of rules to know. ## What you gain, and when it pays Reasons that still justify a replacement in ASP.NET Core 10: - an existing body of container modules and registrations, for example from an older application; - **child containers or lifetime scopes per tenant**, with registrations that differ per tenant; - **property injection**, interception or richer conditional registration that the built-in container deliberately omits. Reasons that no longer do: - choosing an implementation by name: **keyed services** (`AddKeyedScoped`, .NET 8) cover it; - registering by convention or adding decorators: **Scrutor** does it on top of the built-in container. A reasonable rule: stay on the built-in container until a concrete requirement from the first list appears, and record that requirement next to the `UseServiceProviderFactory` line so the next upgrade can re-evaluate it.

  • Why does builder.Services.AddAutofac() not switch a .NET 10 WebApplication to Autofac?
    `AddAutofac` only adds `IServiceProviderFactory<ContainerBuilder>` as a singleton service. The generic host behind `WebApplication` does not look for a factory among registered services; it uses the one passed to `UseServiceProviderFactory`. The package's own XML documentation marks `AddAutofac` as working only for pre-ASP.NET Core 3.0 hosting.
  • After switching containers, how do you keep a startup check like ValidateOnBuild?
    Use whatever verification the replacement container offers, and add an integration test that builds the app and resolves the key services: every handler, controller dependency and hosted service. That test exercises the real container, so it catches missing registrations and lifetime problems regardless of which container is underneath.

  • builder.Services.AddAutofac() is enough to switch a .NET 10 WebApplication to Autofac.
  • ValidateOnBuild keeps checking registrations after a third-party factory is plugged in.
  • ConfigureContainer callbacks run immediately, before later builder.Services registrations.
  • Registrations made with builder.Services are lost once another container is used.
  • A third-party container is needed to choose an implementation by key in .NET 10.

Assumes ASP.NET Core 10 on .NET 10 with WebApplicationBuilder: the factory is set through builder.Host, and keyed services (since .NET 8) remove one historic reason for a third-party container.

open as a page

With Scrutor in ASP.NET Core, what does each step of services.Scan(s => s.FromAssemblyOf<GetShipmentHandler>().AddClasses(...).AsImplementedInterfaces().WithScopedLifetime()) do?

level: juniorimportance: should knowfreq 36%

basics

~10 s

Scan reflects over the assembly containing GetShipmentHandler, AddClasses picks its public non-abstract classes (optionally filtered), AsImplementedInterfaces registers each class under every interface it implements, and WithScopedLifetime makes those registrations scoped.

open as a page

With Scrutor 7 in ASP.NET Core, which Scan defaults surprise teams (lifetime, visibility, duplicates and interfaces), and how do you override each?

level: middleimportance: should knowfreq 28%

basics

~10 s

Without a lifetime call Scrutor registers transient; AddClasses() skips internal classes; the default RegistrationStrategy.Append duplicates anything already registered; and AsImplementedInterfaces registers every interface, IDisposable included. Override with With*Lifetime, publicOnly: false, UsingRegistrationStrategy and a predicate.

open as a page

With Scrutor, how does services.Decorate(typeof(IQueryHandler<,>), typeof(CachingQueryHandler<,>)) wrap forty scanned handlers, and what makes it throw or skip registrations?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Decorate walks the descriptors registered so far, re-registers each matching handler under a generated key and replaces it with a factory that builds CachingQueryHandler around it, keeping its lifetime. It throws DecorationException when nothing matches; open generic registrations are skipped.

open as a page