Logo

dev-resources.site

for different kinds of informations.

Dependency injection validation error in ASP.NET Core projects

Published at
1/11/2025
Categories
aspnet
dotnetcore
csharp
Author
alechka
Categories
3 categories in total
aspnet
open
dotnetcore
open
csharp
open
Author
7 person written this
alechka
open
Dependency injection validation error in ASP.NET Core projects

Recently I was digging into some dotnet project and while (days of) debugging realised, that some of singleton projects actually depends on the scoped ones.

Problem

Code example for better understanding:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddScoped<Scoped>();
builder.Services.AddSingleton<Singleton>();

var app = builder.Build();


class Scoped
{
    public string Test { get; set; } = "It works! But shouldn't";
}

class Singleton(Scoped sc)
{
    public void Print()
    {
        Console.WriteLine(sc.Test);
    }
}

Enter fullscreen mode Exit fullscreen mode

This code started and didn't produce any errors. But of course, some services are scoped for a reason (EF Context for example), so when they don't you have a lot of really hard figure out bugs.

So what's happening?

Let's dive deeper inside builder.Build() here. It's actually using Build method from HostApplicationBuilder class. There is a code inside it:

ServiceProviderOptions? serviceProviderOptions = null;
if (!settings.DisableDefaults)
{
    HostingHostBuilderExtensions.ApplyDefaultAppConfiguration(_hostBuilderContext, Configuration, settings.Args);
    HostingHostBuilderExtensions.AddDefaultServices(_hostBuilderContext, Services);
    serviceProviderOptions = HostingHostBuilderExtensions.CreateDefaultServiceProviderOptions(_hostBuilderContext);
}

_createServiceProvider = () =>
{
    // Call _configureContainer in case anyone adds callbacks via HostBuilderAdapter.ConfigureContainer<IServiceCollection>() during build.
    // Otherwise, this no-ops.
    _configureContainer(Services);
    return serviceProviderOptions is null ? Services.BuildServiceProvider() : Services.BuildServiceProvider(serviceProviderOptions);
};
Enter fullscreen mode Exit fullscreen mode

So yep, Services.BuildServiceProvider() without parameters doesn't validate services by default. But there are some options that comes from HostingHostBuilderExtensions. Ok, sometimes I like Microsoft naming. When you see something named as HostingHostBuilderExtensions, you can be absolutely sure, that things are completely screwed, and you are in a really deep water.

But this surprisingly is the end of the long journey. Here it is:

internal static ServiceProviderOptions CreateDefaultServiceProviderOptions(HostBuilderContext context)
{
    bool isDevelopment = context.HostingEnvironment.IsDevelopment();
    return new ServiceProviderOptions
    {
        ValidateScopes = isDevelopment,
        ValidateOnBuild = isDevelopment,
    };
}
Enter fullscreen mode Exit fullscreen mode

So, the actual difference is Environment. Some folks in asp.net core development team decided to reduce building time of dependency injector containers by making validation dependant on, in fact, an environment variable. And havenโ€™t provided any documentation.

Dev screnshot
Prod screenshot

TL;DR

Service validation in ASP.NET Core apps depends on environment. Guys in Microsoft made some optimizations, so validations works only if you are running your app in development environment. So be sure to set ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT to Develompent when you are debugging your code.

aspnet Article's
30 articles in total
Favicon
The Future of ASP.NET: What to Expect
Favicon
DevExpress - Enhancing ASP.NET Web Forms with the ASPxGridView Control
Favicon
Advanced Search in .NET with Elasticsearch(Full Video)
Favicon
Introducing Brick SaaS Starter Kit - Launch SaaS Products Faster
Favicon
Using server sent events in ASP.NET
Favicon
Important Links
Favicon
Serverless OAuth2/OIDC server with OpenIddict 6 and RDS Aurora v2
Favicon
Learning in Reverse: How I Would Learn ASP. Net Core and Entity Framework If I Could Go Back In Time
Favicon
Dependency injection validation error in ASP.NET Core projects
Favicon
Agrupamiento de datos de una lista usando LINQ en C#
Favicon
Asp .Net: Create a Simple 'Web User Control'
Favicon
[ASP.NET] ๅฆ‚ไฝ•ๅฐŽๅ‘ๅˆฐ้Œฏ่ชค้ ้ข
Favicon
DevExpress - Simplifying Server-to-Client Data Transfer with ASPxCallback JSProperties
Favicon
Asp.net
Favicon
[ASP.NET] ่จญ็ฝฎ่ˆ‡ๅ–ๅพ— Web.config ่‡ชๅฎš็พฉ่ณ‡ๆ–™
Favicon
How to Hire Dedicated .NET Developers
Favicon
Permission-Based Authorization in ASP.NET Core: A Step-by-Step Guide
Favicon
Permission-Based Authorization in ASP.NET Core: A Step-by-Step Guide
Favicon
Dependency Container and Services Lifetimes (ะะฐ ั€ัƒััะบะพะผ)
Favicon
Containerize ASP.NET Core API, Entity Framework with SQL Server, Let's Encrypt, Docker, and Nginx (Part 1)
Favicon
differences of Transient and scoped in ASP NET
Favicon
ASP.NET8 using DataTables.net โ€“ Part6 โ€“ Returning additional parameters in AJAX
Favicon
ASP.NET8 using DataTables.net โ€“ Part4 โ€“ Multilingual
Favicon
ASP.NET8 using DataTables.net โ€“ Part8 โ€“ Select rows
Favicon
ASP.NET8 using DataTables.net โ€“ Part3 โ€“ State saving
Favicon
ASP.NET8 using DataTables.net โ€“ Part7 โ€“ Buttons regular
Favicon
ASP.NET8 using DataTables.net โ€“ Part5 โ€“ Passing additional parameters in AJAX
Favicon
ASP.NET8 using DataTables.net โ€“ Part9 โ€“ Advanced Filters
Favicon
ASP.NET8 using DataTables.net โ€“ Part2 โ€“ Action buttons
Favicon
ASP.NET 8 โ€“ Multilingual Application with single Resx file โ€“ Part 3 โ€“ Forms Validation Strings

Featured ones: