✅ 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:
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
because builder.Build buils the di container
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
i gotta go but reading this might answer your question https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/extensibility?view=aspnetcore-8.0
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.
i will read it and we can continue talking when you are available , thank you
Does it really matter if middleware is transient or scoped? I mean it called once per request anyway
no that was just an example what matters for me why all of the configration etc not being done only on the app level
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()
)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