How does ValidateOnBuild help catch dependency injection configuration errors immediately at application startup rather than at runtime?
Short answer
When ValidateOnBuild is enabled (on by default in Development via the default host builder), calling builder.Build() eagerly validates that every registered service's dependencies can actually be resolved, throwing an immediate, clear exception at startup for missing…
Advertisement
AModel answer
When ValidateOnBuild is enabled (on by default in Development via the default host builder), calling builder.Build() eagerly validates that every registered service's dependencies can actually be resolved, throwing an immediate, clear exception at startup for missing registrations rather than a confusing failure later when a specific code path first tries to resolve that broken service -- combined with ValidateScopes (also on by default in Development), it also catches captive dependency issues at the same point.
var builder = WebApplication.CreateBuilder(args);
// In Development, ValidateOnBuild and ValidateScopes run automatically at Build() time,
// catching missing registrations and captive dependencies immediately
var app = builder.Build(); // throws here if misconfigured, not later at runtimeReal-world example
A missing service registration that would have caused a runtime crash only when a specific rarely-hit code path executed is instead caught immediately at application startup during local development, thanks to ValidateOnBuild eagerly checking the entire dependency graph.
Likely follow-ups
- Why are these validations typically disabled in Production for performance reasons?
- How do you explicitly enable them in Production if you want the extra safety despite the cost?
Related topics