Search code examples
c#asp.net-coreasp.net-core-6.0asp.net-core-minimal-hosting-model

Why migrate to the ASP.NET Core 6 minimal hosting model?


I'm upgrading a system from ASP.NET Core 5 to 6. I've read the migration guide for the new "minimal hosting model".

The docs say the new way is preferred and recommended, but the old way is supported - so I don't need to change. They also state the old way is useful for "advanced" scenarios, without mentioning details.

There's lots of docs / blogs / SO questions about how to use the new way - but no mention of why. An "app in just four lines" is given as a reason, but that is insufficient cause to migrate a working system.

I'll upgrade to v6, but am undecided about the hosting model. How would I or my working production system benefit?

If you migrated a production system to the new hosting model, would you please share advice about whether it was worth it? What are the pros (and cons) of the new approach? Thanks!


Solution

  • The biggest change with the new hosting model is a style change. The callbacks on IHostBuilder have been change to a more straight line model (instead of adding callbacks and then building the host, it's write code to configure then build the host). That allows you to get in between initialization and write imperative logic. One of the bigger ways this shows up is async initialization. You can just write code that await some asynchronous configuration, then use the result of that to add a service. This is really hard to do with callbacks since we're need to add async Configure/ConfigureServices and many other things. This model just lets you write code.

    The sample in the migration guide that shows how to keep the Startup class but still use the new WebApplicationBuilder illustrates this best:

    using Microsoft.AspNetCore.Builder;
    
    var builder = WebApplication.CreateBuilder(args);
    
    var startup = new Startup(builder.Configuration);
    
    startup.ConfigureServices(builder.Services);
    
    var app = builder.Build();
    
    startup.Configure(app, app.Environment);
    
    app.Run();
    

    It's extremely clear an obvious when these methods are being called and how Startup is constructed.

    In the end, it's really a pattern change where you might not see a huge benefit if you have already fully understand and programming around the existing model. That's why it's optional.