Program.cs in ASP.NET Core

What would be the use of Program.cs file in ASP.NET Core application! ASP.NET Core web application requires a host to be executed. We can configure a web hosting environment in Program.cs.

public static void Main(string[] args)
{
 BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseIISIntegration()
 .UseStartup<Startup>()  
    .Build();
What is Program.cs file?

Program.cs file is the entry point of the application. This will be executed first when the application runs, there is a public static void Main method, Whatever code you write inside that method will be executed in that same order, In asp.net core application we normally call all "hosting related setting and startup.cs file methods" from that Main() method.

Can we run application without Program.cs?

No, it will give an build error, will not allow to run the application.

In ASP.NET Core there is a new way to build web host configuration. Now we can set defaults of the web host configuration using WebHost.CreateDefaultBuilder()

This is how the Program.cs file look like

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
 BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseIISIntegration()
 .UseStartup<Startup>()  
    .Build();
}

In public static void Main() of Program class where we can create a host for the web application, earlier tutorial we have explained about asp.net core Startup.cs class

var host = new WebHostBuilder();
// Now 
IWebHostBuilder host = WebHost.CreateDefaultBuilder(args)
//CreateDefaultBuilder is a static method now create the new instance
// finally call 
host.Run();
            

Simply create a .net core console application and run the above code to understand how program file is used.

In visual studio 2022 there is no startup file, we need to do some configuration changes in Visual Studio 2022 for .Net Core.

You may be interested to know how to implement dependency injection directly from program.cs file

Asp.Net Core C# Examples | Join Asp.Net MVC Course