It also exposes an IServiceCollection directly for adding services to the DI container. So whereas with the generic host you had to do
var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.ConfigureServices(services =>
{
services.AddRazorPages();
services.AddSingleton<MyThingy>();
})
with WebApplicationBuilder you can do
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddSingleton<MyThingy>();
Similarly, for logging, instead of doing
var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.ConfigureLogging(builder =>
{
builder.AddFile();
})
you would do:
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddFile();
This has exactly the same behaviour, just in an easier-to-use API. For those extension points that rely on IHostBuilder or IWebHostBuilder directly, WebApplicationBuilder exposes the properties Host and WebHost respectively.
Those latter two points are very much related. In ASP.NET Core 3.x and 5, the IEndpointRouteBuilder is used to add endpoints by calling UseEndpoints() and passing a lambda to it, for example:
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
There's a few complexities to this .NET 3.x/5 pattern for people new to ASP.NET Core:
The middleware pipeline building occurs in the Configure() function in Startup (you have to know to look there)
You have to make sure to call app.UseRouting() before app.UseEndpoints() (as well as place other middleware in the right place)
You have to use a lambda to configure the endpoints (not complicated for users familiar to C#, but could be confusing to newcomers)
WebApplication significantly simplifies this pattern:
app.UseStaticFiles();
app.MapRazorPages();
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (