.NET › Generic Host

How does the Generic Host's dependency validation (ValidateOnBuild and ValidateScopes) help catch DI configuration errors early?

Advanced

Answer

When ValidateOnBuild is enabled (on by default in Development environment via CreateApplicationBuilder/CreateDefaultBuilder), calling host.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. ValidateScopes (also on by default in Development) enables the captive dependency detection discussed earlier, catching Singleton-depends-on-Scoped configuration errors immediately.
var builder = Host.CreateApplicationBuilder(args);
// In Development, these validations run automatically at Build() time:
// - ValidateOnBuild: catches missing service registrations immediately
// - ValidateScopes: catches captive dependency (Singleton -> Scoped) issues

var host = builder.Build();  // throws here if misconfigured, not later at runtime
Real-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.

Common 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?