✅ ASP.NET Core: Confusion with builder.Services.AddTransient() and App Lifetime Management

I'm new to ASP.NET Core, and I'm encountering some confusion regarding service registration. In the code snippet below:
c#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<RequestCultureMiddleware>();
var app = builder.Build();
c#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<RequestCultureMiddleware>();
var app = builder.Build();
We see that builder.Services.AddTransient<RequestCultureMiddleware>() is used to register the RequestCultureMiddleware service with a transient lifetime. However, I understand that the WebApplication.CreateBuilder(args) method builds the application configuration, while service registration is performed at the application level using app. My question is: Why can't we register services like RequestCultureMiddleware directly with app.Services.AddTransient<RequestCultureMiddleware>() instead of using builder.Services? What's the underlying principle behind this separation?
8 Replies
sibber
sibber3mo ago
because builder.Build buils the di container
steven preadly
steven preadly3mo ago
yes i understand this part but there are some things that can be done only on the builder level while it cant be done on the app level like including a custom middleware class as a transient
sibber
sibber3mo ago
Factory-based middleware activation in ASP.NET Core
Learn how to use strongly-typed middleware with a factory-based activation implementation in ASP.NET Core.
steven preadly
steven preadly3mo ago
i will read it and we can continue talking when you are available , thank you
blueberriesiftheywerecats
Does it really matter if middleware is transient or scoped? I mean it called once per request anyway
steven preadly
steven preadly3mo ago
no that was just an example what matters for me why all of the configration etc not being done only on the app level
Pobiega
Pobiega3mo ago
builder is your app before it gets finalized. Thats where you register your services and do your setup imagine baking a cake builder is your bowl of ingredients you add stuff there, before finally pouring your mix into a cake form and baking it (.Build())
steven preadly
steven preadly3mo ago
So that's why configurations are done at the builder level as an example configuration of new middlewears correct I have another question what should I know about the builder and app for not wasting my time exploring things that I will not use
Want results from more Discord servers?
Add your server