Validate that your DI Container can be created in ASP.NET Core

2/3/2025
1 minute read

The .NET provided DI container has some means to check if the container can be created. This is useful to ensure that all dependencies can be resolved and that the container is correctly configured. Let's have a quick look.

Verify that the container can be created

Let's start with the simple code:

builder.Host.UseDefaultServiceProvider((_, options) =>
{
    options.ValidateScopes = true;
    options.ValidateOnBuild = true;
});

This code will enable the validation of scopes and the validation of the container when it is built. If not configured properly, the container will throw an exception. This will be done, by default, if the current environment is Development (as mentioned by @kapsiR - this is due to performance reasons). So if you use different environment names, you might want to enable that check for your environment.

As a matter of fact, I like to keep that setting enabled over all environments, as it helps to catch issues early on. You know, fail fast.

Simple DI - Container

This blog post will show you a very simple Dependency Injection container.

This will give a better understanding of what Dependency Injection is and how it is done. And sure we will see how this is related to IoC - Inversion of Control.

Verifying your DI Container

Microsoft's integrated dependency injection (short DI) container is very powerful, but there are also certain pitfalls. In this article, I will show you what some of the pitfalls are and how you can verify them.

Structure and order your DI container

Does your Dependency Injection container is one big pile of method calls one after the other? Are there 50 lines of just AddScoped, AddTransient, and so on? Well, let's fix this.

We can utilize extension methods to make an order to that mess!

An error has occurred. This application may no longer respond until reloaded. Reload x