In this article, we are going to explain how to access the configuration when the application is starting and how to retrieve services like IConfiguration
and IWebHostEnvironment
in this new setup.
Let’s start.
Farewell to Startup.cs
In earlier versions of .NET, developers utilized the Startup.cs
class to configure services and middleware. However, with the arrival of .NET 6, the traditional Startup.cs
class is no longer required, and its days are numbered. Instead, we embrace the WebApplicationBuilder
class, which offers a more straightforward and flexible configuration approach.
Introducing WebApplicationBuilder
The WebApplicationBuilder
is a new way to set up and configure the ASP.NET Core web application in .NET 6 and later. It provides an elegant and concise solution for developers to specify services, middleware, and other configurations.
Access Configuration When Applications Starts
In the past, within the Startup.cs
class, developers used to receive the IConfiguration
and IWebHostEnvironment
objects via constructor injection. However, in the new WebApplicationBuilder
approach, these objects are accessible directly from the builder and the application.
Here’s how we can access configuration services in the new .NET 6 setup:
var builder = WebApplication.CreateBuilder(args); // Accessing IConfiguration and IWebHostEnvironment from the builder IConfiguration configuration = builder.Configuration; IWebHostEnvironment environment = builder.Environment; builder.Services.AddControllers(); ... app.Run();
Here, we demonstrate how to access IConfiguration
and IWebHostEnvironment
from the WebApplicationBuilder
. The builder provides direct access to these objects, making configuration tasks more straightforward.
Conclusion
The transition from Startup.cs
to WebApplicationBuilder
in .NET 6 represents a shift towards a more modern and efficient approach to configuring ASP.NET Core web applications. Embracing this change allows developers to access IConfiguration
and IWebHostEnvironment
directly from the builder, streamlining the configuration process.
By leveraging the power of WebApplicationBuilder
, developers can take full advantage of the enhancements introduced in .NET 6, ensuring their applications are well-prepared for the future.