Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use "using" statement around BuildWebHost?

In ASP.NET Core 2.x, the best practice is to have a method called BuildWebHost that is called in the app's main entry point (see the MSDN article Hosting in ASP.NET Core):

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

IWebHost is IDisposable, so in the spirit of being a good .NET citizen, would it be advisable to surround BuildWebHost with a using statement?

public class Program
{
    public static void Main(string[] args)
    {
        using (var host = BuildWebHost(args))
        {
            host.Run();
        }
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
like image 617
Whitney Kew Avatar asked Aug 26 '26 14:08

Whitney Kew


1 Answers

No. Use it as is. IWebHost implements IDisposable because it is and can be used in other ways, where you may need to manually dispose of it. However, in the context here, it's the whole kit and kaboodle. It is created when the program starts and continues to be used until the program ends.

As a slightly better explanation, understand that the only reason to dispose of resources is to remove them from memory while the application is continuing to run. Eventually the GC will get rid of abandoned resources whether you dispose or not, but you should never rely on the GC to clean up after you. If you no longer need a resource, you dispose of it, in order to reduce the continued resource load of your application, again, while it's continuing to run.

When your application ends, all associated resources go away with it, as it's all tied to the process. If there's no process, there's nothing left in RAM. Hence why it's unnecessary to manually dispose of IWebHost in this context. Since it will be need until the application ends, and when the application ends, it will be completely gone, no matter what, disposing manually buys you nothing.

like image 174
Chris Pratt Avatar answered Aug 29 '26 15:08

Chris Pratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!