.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.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
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.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some .NET Help?
Search fiverr to find help quickly from experienced .NET developers.