As everyone know that 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.
Please help me out to understand in deep.
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.
Those methods are called by the ASP.NET Core framework. Note that in your Main
method you have this call:
.UseStartup<Startup>()
Where you specify the class to use for the startup, in this case Startup
. The ConfigureServices
and Configure
methods are called by convention. If those methods are found in the class specified in the UseStartup
extension, they will be called.
Lets take a step back and try to understand what are we trying to do here - We are setting Up the Host and Host originates the request pipeline. Now both Configure and Configure services are like the rooms where the requests are configured through middleware or services.
Now as you built the Host and Ran it from Program.cs and injected StartUp as already said, using reflection, stitches up the Request Pipleline origin and configured with these two methods so that it can handle all the requests
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With