是否应在ASP.NET Core 2.x中为BuildWebHost添加using语句?
BuildWebHost in a using statement in ASP.NET Core 2.x? Great question—let's break this down clearly!
The short answer is: No, you don't need to wrap BuildWebHost in a using statement, and it’s not part of ASP.NET Core’s official best practices.
Why this isn’t necessary
Even though IWebHost implements IDisposable, the Run() method handles resource cleanup automatically for you. Here’s what happens under the hood:
- When you call
BuildWebHost(args).Run(), theRun()method blocks the main thread until the app receives a shutdown signal (like Ctrl+C, an OS termination request, or stopping the app in IIS). - Once the shutdown signal is triggered,
Run()will properly dispose theIWebHostinstance, releasing all underlying resources (such as HTTP listeners and registered services) without you needing to manage it explicitly.
Official Reference Example
The standard, recommended approach from Microsoft matches the code you shared:
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
Wrapping this in a using block would technically work, but it’s redundant. The Run() method already guarantees the host is disposed after exiting, so adding using just adds unnecessary boilerplate with no extra benefit.
When would you use using?
The only scenario where explicit using makes sense is if you’re not calling Run()—for example, when creating a host for testing, or when you need to start/stop the host programmatically without blocking the main thread. In those cases, you’d manage disposal manually:
using (var host = BuildWebHost(args)) { host.Start(); // Perform custom work here host.StopAsync().Wait(); }
But for a typical ASP.NET Core application’s main entry point, this isn’t required.
内容的提问来源于stack exchange,提问作者Whitney Kew

