With FluentValidation's AddValidatorsFromAssemblyContaining in ASP.NET Core, what lifetime do validators get, and what breaks if you register them as singletons?
answer
- default ServiceLifetime.Scoped
- registered as IValidator<T> and as itself
- public non-abstract unless includeInternalTypes
- singleton captures scoped dependencies
- ValidateScopes catches it in Development
basics
~20 sValidators are registered scoped by default. Registering them as singletons is safe only if they depend on nothing scoped; a singleton validator that takes a DbContext or a scoped credit-bureau client captures one instance for the whole app.
solid answer
~50 s`AddValidatorsFromAssemblyContaining<T>(lifetime = ServiceLifetime.Scoped, filter = null, includeInternalTypes = false)` registers each public, non-abstract validator as `IValidator<T>` and as its concrete type, with a scoped lifetime unless you pass another. Scoped fits web apps: one validator per request, free to depend on scoped services such as a `DbContext` or a scoped credit-bureau client. Singletons are tempting because validators build their rules in the constructor, but a singleton that takes a scoped dependency holds the first instance forever. In Development, ASP.NET Core turns on scope validation, so the host fails at startup with "Cannot consume scoped service ... from singleton ...". Outside Development that check is off by default, and the captured `DbContext` gets used concurrently by many requests. FluentValidation's own docs call transient the simplest and safest choice and advise singletons only for validators with no request-bound dependencies.
go deeper
Know that AddValidatorsFromAssemblyContaining registers validators in DI as scoped and that you inject them as IValidator<T>.
Explain what the scan registers (interface and concrete type), the lifetime parameter, includeInternalTypes and filter.
Diagnose a captive DbContext in a singleton validator, explain why only Development caught it, and pick a lifetime per dependency graph.
Set conventions for validator dependencies (pure rules versus I/O-backed rules) so lifetimes stay simple and validators remain testable.
## What the scan registers `AddValidatorsFromAssemblyContaining<T>()` and its siblings (`AddValidatorsFromAssemblyContaining(Type)`, `AddValidatorsFromAssembly`, `AddValidatorsFromAssemblies`) come from the `FluentValidation.DependencyInjectionExtensions` package. All share the same optional parameters: | Parameter | Default | Effect | |---|---|---| | `lifetime` | `ServiceLifetime.Scoped` | lifetime of every registration | | `filter` | `null` | a predicate on each scan result, to skip validators | | `includeInternalTypes` | `false` | also register `internal` validators | For each validator found, the scan adds: 1. `IValidator<LoanApplication>` mapped to `LoanApplicationValidator`, via `TryAddEnumerable`, so the same pair is never added twice. 2. `LoanApplicationValidator` mapped to itself, via `TryAdd`. Only the assembly that contains `T` is scanned. Validators in another project need their own call, and `internal` validators are skipped unless `includeInternalTypes: true`. ## Why scoped is the default A web request opens one DI scope. A **scoped** validator is created once per request and can depend on other scoped services: ```csharp public class LoanApplicationValidator : AbstractValidator<LoanApplication> { public LoanApplicationValidator(LendingDbContext db, ICreditBureauClient bureau) { RuleFor(x => x.Amount).GreaterThan(0); RuleFor(x => x.ApplicantId) .MustAsync(async (id, ct) => !await db.Blacklist.AnyAsync(b => b.ApplicantId == id, ct)); RuleFor(x => x.NationalId) .MustAsync((nid, ct) => bureau.HasFileAsync(nid, ct)); } } ``` `LendingDbContext` is scoped (registered with `AddDbContext`). As long as the validator is scoped or transient, each request gets a validator holding that request's context. ## What a singleton breaks Registering with `AddValidatorsFromAssemblyContaining<LoanApplicationValidator>(ServiceLifetime.Singleton)` changes the picture: - The container builds the validator **once**, from the root provider. Its constructor receives one `LendingDbContext` that lives until the app shuts down and is shared by every request. - `DbContext` is not thread-safe, so concurrent requests can fail with EF Core's concurrent-use exception, see stale tracked entities, or leak memory as the change tracker grows. - In **Development**, `WebApplicationBuilder` turns on `ValidateScopes` and `ValidateOnBuild`. Building the host then fails with the container's "Cannot consume scoped service ... from singleton ..." error, naming the context and the validator. That startup failure is the good outcome. - In **Production**, those checks stay off unless you enable them, so the captive dependency ships silently. The FluentValidation documentation states the trade-off directly: only use singleton validators if you know nothing transient or request-scoped is injected, and treat transient as the simplest and safest option. ## Choosing a lifetime - **Scoped (default):** right for most web apps; dependencies can be request-scoped. - **Transient:** a new validator per resolution; safest when a validator is resolved in several places, at the cost of rebuilding rules more often. - **Singleton:** only for validators with no dependencies, or with singleton-safe ones such as `TimeProvider`. If you need it for performance, measure first; rule construction is rarely the bottleneck next to a database or HTTP call. ## Related traps - **Injecting a validator into a singleton service** (a hosted worker, a singleton cache) captures it the same way. Create a scope with `IServiceScopeFactory` and resolve `IValidator<T>` inside it. - **Instance filters.** A filter object created once at startup must not hold a scoped validator; resolve it per request from `HttpContext.RequestServices` instead. ## What interviewers listen for - The default (`Scoped`) and the parameters that change it. - The captive-dependency explanation with a concrete scoped service. - How Development scope validation exposes it, and why Production may not.
- Why did the app fail at startup only on a developer machine after switching validators to singleton?`WebApplicationBuilder` enables `ValidateScopes` and `ValidateOnBuild` in the Development environment. Building the provider then detects that a singleton `IValidator<LoanApplication>` depends on a scoped `DbContext` and throws. Other environments keep those checks off by default, so the same code starts and fails later under concurrent load.
- How do you keep one validator out of the assembly scan?Pass a `filter` predicate: `AddValidatorsFromAssemblyContaining<LoanApplicationValidator>(filter: r => r.ValidatorType != typeof(LegacyLoanValidator))`. The predicate receives each `AssemblyScanResult`, and returning `false` skips both registrations for that validator. You can then register it by hand with a different lifetime if needed.
A scoped validator is like a loan officer assigned to one applicant's file for the day: they use that day's paperwork and hand it back. A singleton validator is one officer who keeps the first applicant's folder on the desk and reads from it for every later customer.
- AddValidatorsFromAssemblyContaining registers validators as singletons by default.
- A singleton validator gets a fresh DbContext for every request automatically.
- Scope validation errors appear in every environment, so Production would fail at startup too.
- The scan also finds internal validators unless you exclude them.
- Validators must be singletons because building rules per request is too slow.