The Main method of Program.cs is the entry point of application. As you can see in the .NET Core default code created when we create any project.
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
And in startup class we have two In-build method i.e ConfigureServices
and Configure
as shown below.
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}
I just want to know that how these methods is invoked. As we know that to invoked any method we have to create a object of the class and using that object we can execute the method, then how these(ConfigureServices
and Configure
) methods execute without creating any object.
As an overly simplified explanation,
WebHost.CreateDefaultBuilder(args)
method call returns an object for default webhost builder which implements IWebHostBuilder
. Then UseStartup()
extension method configures created webhost builder using the Startup class you provide. UseStartup()
method can identify your startup class since you specify as the generic argument. UseStartup() cantains the implementation to invoke ConfigureServices
and Configure
methods which you provide by using the reflection. Note that to invoke a method one can use reflection also other than creating an instance of a class.