Search code examples
c#.net-coreasp.net-core-webapiasp.net-minimal-apis

Is it good to create Startup.cs in .NET Core Projects rather than registering services in Program.cs?


I am working on an ASP.NET Core 6 Minimal API project. Why was the Startup.cs file removed from newer versions of .NET Core? Is there a specific reason for this change?

Additionally, is the integration of service and middleware registration into the Program.cs file, as shown in the provided code snippet, considered the recommended and more intuitive approach for configuring applications in the latest versions of.NET Core?

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = CreateHostBuilder(args).UseDefaultServiceProvider(x => x.ValidateScopes = false).Build();
        await host.RunAsync();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
}

Solution

  • Microsoft has dumped the old template with Startup.cs file and it is now rather deprecated practice - if you have great registration logic (Dependency Injection registartion) and configuration (configuring the app from config files, etc.), you could consider separate class with static methods or extension methods on IServiceCollection to register you application-wise service and apply your configs.

    But new way is to have single startup code located in Program.cs which has all. There you get instance of WebHostBuilder, on which you can configure DI (WebHostBuilder.Services). Using Build() method, you get the application object, that will run the ASP.NET app (with Run() method). Using the app object you can also register middlewares and endpoints.

    Here we come to another improvement in new .NET - minimal APIs, where you can define endpoints directly using the app object, for instance: app.MapGet("/", () => "Hello World");, so no more need for controllers - again, as long as this code inside endpoints is small and concise, it could be placed there. But in more complex logic I recommend creating separate controller files anyway.

    So there it is - there are new ways possible to create your ASP.NET Web API, but as with everything - where to use it and how - it depends :)