.net core tutorials

Using IHost .net core console applications

In a previous post I discussed how we can use Configuration API in .net core console application to retrieve custom configuration settings from a Json file. Although this example is a convenient feature making use of the Microsoft.Extensions.Configuration namespace.

In this post I will provide an example of how to develop .NET Core console applications using generic IHost to develop headless services.

Code available on Github

One of the most common uses for a Console Application is to build what is known as headless services, this is particulary common when working with Docker containers and Kubernetes (K8S).Using headless services, it is possible to create a service grouping that does not allocate an IP address or forward traffic, enabling you to definitively control what specific pods you connect and communicate with.We can develop headless services using .net core console applications by making use of the .net core generic host.

What is .net core generic host

A common scenario or use case for headless services is to run in a Fire And Forget asynchronous pattern, which facilitate background processing tasks, perhaps handling messages on a queue for example, common in a cloud native, container based architectures.

The goal of the Generic Host is to decouple the HTTP pipeline from the Web Host API to enable a wider array of host scenarios. The Generic Host is new in ASP.NET Core 2.1 and isn’t suitable for web hosting, but is ideally used for Console Applications which are typically used to develop headless services.

The Generic Host library is available in Microsoft.Extensions.Hosting namespace and provided by Microsoft.Extensions.Hosting package.

To add the namespace using the .net core CLI

 

Introducing IHost and the HostBuilder

In .NET Core 2.1 Generic Host enables developers easily set up cross-cutting concerns for non-web based applications including:

  • Configuration
  • Logging
  • Dependency Injection (DI)

The IHost interface offers a number of benefits and features:

  • Graceful shut down
  • Dependency Injection
  • Logging
  • Configuration

These features are particularly important when developing complex data processing tasks in Docker containers. Especially graceful shut down, as it helps to keep application state consistent.



Implement IHost in .net core console applications

The IHost interface and the HostBuilder class provide similar experience to the respective IWebHost and WebHostBuilder .net core web developers are familiar with when using ASP.net core.

IHost and HostBuilder are components of a new feature set of .NET Core 2.1, to simplify the creation of console based services by providing a pattern for adding cross-cutting concerns such as dependency injection, configuration and logging.

You need to bear in mind that applications which will implement the IHost interface will typically be required to run asynchronously. This will usually require marking the Main method as async.

In order to continue developing our application we will need to add several more package references

HostBuilder does not provide an extension method enabling the use of a StartUp class

The HostingHostBuilder provides extension methods to configure host services. The following extension available:

  • ConfigureAppConfiguration – Application Configuration
  • ConfigureContainer – Configure the instantiated dependency injection container
  • ConfigureLogging – Configure Logging
  • ConfigureServices – Adds services to the Dependency Injection container
  • RunConsoleAsync – Enables console support
  • UseConsoleLifetime – Listens for shutdown signals
  • UseContentRoot – Specify the content root directory
  • UseEnvironment – Specify the environment

The RunConsoleAsync will start services and wait on an exit signal in the application.



Building a Host

Using the Main method create a HostBuilder and use extension methods to register services with DI, read configuration and configure the logging for your application.

To configure the Host we will use ConfigureHostConfiguration to initialize the IHostingEnvironment for use later in the build process. Environment variable configuration isn’t added by default, so we have to call AddEnvironmentVariables on the host builder to configure the host from environment variables. AddEnvironmentVariables accepts an optional user-defined prefix, by convention use your application name in our example we’ve declared a constant string value with _prefix set with the application name.

Use the ConfigureAppConfiguration configuration providers to construct the final representation of configuration values for our application.

In the example below we read the configuration values from an appsettings.json file first, followed by environment variables and finally from any arguments passed into the application.

ConfigureServices is where we configure the services we want our application to run, registering services with the ServiceCollection. Registration is performed using extension methods on the ServiceCollection and once complete, enabling DI in our application.



Using IHostedService

The actual implementation of the service is defined using IHostedService interface. When an application is started, it will call StartAsync method.

At shutdown, StopAsync is called and the service cleans up a little before the application is killed.

IHostedService implementation defined and registered with DI container using ConfigureServices

Usually in Linux daemons, your service implementation will be a Singleton class – only one instance of the service for the application lifetime.

It also adds the configuration POCO (Plain Old C# Object) to the the services for dependency injection. This implements the IOption interface in .NET Core, which can take a type that it will attempt to bind CLI parameters and environment variables to based on the field name.



Summary

Console application with one or more IHostedServices are ideal for developing Headless Services for data processing running in Docker containers. When the container is shut down, the processing can stop gracefully.

Dependency Injection gives you many options to test your code, enabling separation of concerns.

There are a number of concepts introduced with Generic Host, which are essential to simplify the development of microservices . A single common pattern for web applications as well as services, with easy access to things like DI, logging and configuration is extremely welcome.



Additional Resources

Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.

Affiliate Disclaimer

Disclosure: Please note that some of the links included in the blog posts are affiliate links, which means I will earn a commission if you decide to make a purchase.

I only include affiliate links to products, services and companies that I have personal experience and have actually used. I only recommend them because they are helpful and useful, not because of the small commissions I make if you decide to buy something.

Please do not spend any money on these products unless you feel they are relevant, suitable and will help you achieve your goals.

Buying anyone of these products and the commisions earned will not make me an overnite multi millionaire, but they will help to cover the hosting costs and compensate for the countless hours and effort I put in to create meaningful and valuable free content I provide to help others succeed.

You've also undoubtedly noticed that I also use various advertising networks - unless of of course you're using an Ad blocker, this is also an attempt to reduce my monthly deficit I experience in providing free relevant, valuable and on occassion insightful content for the benefit of others.

I only really make some money if people click on the ads, unless of course you consider 1c per 1000 impressions real money!

Bear in mind just how many impressions I need to make before I can cover my £20 hosting costs a month!

If you are using an adblocker and guilt stricken you can of course donate using any of the buttons below, but I won't be holding my breath.


Buy me a coffeeBuy me a coffee
π