Waiting for the Host to be disposed. Ensure all ‘IHost’ instances are wrapped in ‘using’ block.

Today in this article, we will cover below aspects,

Issue Description

Waiting for the Host to be disposed. Ensure all ‘IHost’ instances are wrapped in ‘using’ block.

Waiting for the Host to be disposed of Ensure all'IHost' instances are wrapped in'using' block.

Resolution

I got this error while using Host builder to create a custom IoC container for the C# console applications.

I found Console Lifetime doesn’t allow the full graceful shutdown of the application. Even using Environment.Exit to fix the issue did not work out.

My HostBuilder example,

     var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {

                     services.AddLogging(configure => configure.AddConsole())
                     .AddTransient<MyApplication>()
                     .AddScoped<IBusinessLayer, BusinessLayer>()
                     .AddSingleton<IDataAccessLayer, CDataAccessLayer>()
                     .AddDbContext<EmployeeContext>(options =>
                     {
                         options.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=master;Trusted_Connection=True;");
                     });

                });

            var host = builder.Build();

I was able to resolve the issue by making the below two changes.

Use Console Lifetime for the console app

Creating a Hostbuilder or CreateDefaultBuilder with ConsoleLifetime provides below functionalities,

  • Listens for Ctrl+C or SIGTERM.
  • Calls IHostApplicationLifetime.StopApplication to start the shutdown process.
  • Unblock extensions like RunAsync and WaitForShutdownAsync.

Waiting for the Host to be disposed Ensure all IHost instances are wrapped in using block

Using IHostApplicationLifetime

Using IHostApplicationLifetime allows consumers to be notified of application lifetime events.

Using StopApplication() helps to gracefully exit the application and doesn’t hang the console application.

Injecting IHostApplicationLifetime using DI approach,

And now you call StopApplication() for any exception or when the operation completes successfully.

internal void Run()
        {
            try
            {
                _logger.LogInformation("Application {applicationEvent} at {dateTime}", "Started", DateTime.UtcNow);

                _business.PerformBusiness();

                _logger.LogInformation("Application {applicationEvent} at {dateTime}", "Ended", DateTime.UtcNow);

                _applicationLifetime.StopApplication();
            }
            catch (Exception ex)
            {
                _applicationLifetime.StopApplication();
            }
        }

Reference:

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *