Published: September 30 2021

.NET - Program Class and Main Method in a Nutshell

Tutorial built with .NET 5.0

Related posts:

The Main() method is the entry point for a .NET application, when an app is started it searches for the Main() method to begin execution. The method can be located anywhere in a project but is typically placed in the Program class.

A .NET web app is run within a host which handles app startup, lifetime management, web server configuration and more. A host is created and launched by calling Build().Run() on a host builder (an instance of the IHostBuilder interface). A generic host builder with pre-configured defaults is created with the CreateDefaultBuilder() convenience method provided by the static Host class (Microsoft.Extensions.Hosting.Host).

The ConfigureWebHostDefaults() extension method configures the host builder for hosting a web app including setting Kestrel as the web server, adding host filtering middleware and enabling IIS integration. For more info on the default host builder settings see https://docs.microsoft.com/aspnet/core/fundamentals/host/generic-host#default-builder-settings.

The x.UseStartup<Startup>() method specifies which startup class to use when building a host for the web app.

A minimal Program class with Main method

This is an example of a minimal .NET Program class with a Main() method that creates and configures a web host using the methods described above. The code is from a tutorial I posted recently on how to create a minimal .NET API by hand from scratch, for more info see .NET 5.0 - Bare Bones API Tutorial.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

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

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some .NET Help?

Search fiverr to find help quickly from experienced .NET developers.



Supported by