.NET Core中Startup.cs的ConfigureServices与Configure方法调用机制问询
Great question—this is one of those "magic" parts of .NET Core that feels opaque at first, but it's actually just the framework handling the busywork for you. Let's break it down step by step:
1. The WebHost does all the heavy lifting
Look at your Main method:
public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>();
When you call .Build() on the IWebHostBuilder, the .NET Core WebHost takes over. The .UseStartup<Startup>() call tells the WebHost: "Hey, use this Startup class to set up the application."
2. How the WebHost handles Startup
During the .Build() process, the WebHost automatically:
- Instantiates the Startup class: It uses the dependency injection container to create an instance of your
Startupclass. Even if yourStartuphas a constructor with dependencies (likeIConfiguration), the framework will resolve and inject those for you. - Calls
ConfigureServicesfirst: This method is invoked to let you register services (like database contexts, custom services, etc.) into the dependency injection container. The framework passes theIServiceCollectionparameter directly to this method. - Calls
Configurenext: After services are registered, the framework calls this method to set up your application's middleware pipeline. It injectsIApplicationBuilder(and other optional services likeIHostingEnvironment) so you can configure things like routing, authentication, static files, etc.
3. Why you don't need to create the Startup instance yourself
This is all part of .NET Core's "convention over configuration" design. The framework follows a set of predefined rules:
- If you specify a
Startupclass via.UseStartup<T>(), the framework expects it to have (at minimum) aConfiguremethod. TheConfigureServicesmethod is optional but widely used. - You don't need to handle instantiation or method calls because the WebHost is designed to manage this lifecycle for you. It's abstracting away the boilerplate code so you can focus on configuring your application.
As a side note, you can even skip the Startup class entirely if you want—you can configure services and middleware directly on the WebHostBuilder:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureServices(services => { // Register your services here instead of in ConfigureServices }) .Configure(app => { // Configure middleware here instead of in Configure });
内容的提问来源于stack exchange,提问作者Pankaj Moriya

