When building applications with .NET's dependency injection container, misconfigured services can lead to runtime exceptions that only surface when a particular code path is executed.
Consider this scenario: you've registered a service with dependencies, but accidentally forgot to register one of those dependencies. Without validation, your application starts successfully, but crashes later when someone tries to use that service:
This only fails when OrderService is first resolved, which might be deep in your application logic or in a rarely-used code path.
Failing fast
A better option is to fail fast and be aware of this problem immediately. This is exactly what the ValidateOnBuild property does. It tells the DI container to validate all registered services during the application startup phase:
Now, instead of a runtime failure later, you get an immediate exception during startup with a clear error message about the missing dependency.
Remark: Be aware, this is not an error during compilation but during application startup.
There's a small startup cost since the container needs to validate all registrations. For most applications, this is negligible, but if you have thousands of services or complex validation logic, you might notice a slight delay in application startup.
ValidateScopes
Related to ValidateOnBuild is the ValidateScopes property, which ensures scoped services aren't resolved from the root container:
Together, these options provide robust validation of your DI configuration.
