Implement Console application shutdown or exit in .NET Core- Guidelines

Today in this article, we shall learn how to Implement Console application shutdown or exit.

The approach mentioned is useful when you are a console application implements the custom Dependency injection.

Today in this article, we will cover below aspects,

I have talked about the approach on how to implement the DI – Dependency injection in nonhost type of application in details like console or windows forms application.

In the implementation, we learned how to DI various services and implement efficient.

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.

Step 1 – UseConsoleLifetime() for the console app

Creating a Hostbuilder or CreateDefaultBuilder with ConsoleLifetime provides below functionalities,

Non-host Apps

var builder = new HostBuilder()

OR

var builder = Host.CreateDefaultBuilder().Build();

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

NET Core Console application shutdown or exit

Step 2- Using IHostApplicationLifetime

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

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

IHostApplicationLifetime supports below properties,

  • ApplicationStarted – When fully started, this events gets triggered.
  • ApplicationStopped – This events gets Triggered when the application host has performed a graceful shutdown.
  • ApplicationStopping -Event get trigger when Host is performing a graceful shutdown. S

Injecting IHostApplicationLifetime using DI approach,

How to shutdown or exit

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 *