.NET Core 3.0's Unified Generic Host

.NET Core 3.0's Unified Generic Host

For years we've all probably grown accustomed to developing ASP.NET Core applications and benefiting from all the goodness the WebHostBuilder provided. Out of the gate with a few simple lines of code it would:

  • Configure Kestrel (Web server used by ASP.NET Core)
  • Load Environment Variables (Prefixed by ASPNETCORE_ or command line arguments)
  • Load Configuration from a variety of sources: appsettings.json, Secret Manager, Command Line arguments, etc
  • Configure logging for console and debugger outputs
  • Setup the Startup class which can be used to configure Dependency Injection.

It was a fantastic application architecture that defined how we approach application development. Inversion of Control (IoC) was baked into our controllers which allowed us to mock our services which made unit testing much easier and as a result code coverage and code quality increased.

Then when we were asked to create a console application, the out of the box code gave us this:

using System;

namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Where's my configuration, dependency injection, and customizable logging? Then starting with .NET Core 2.1 Microsoft added the Generic Host for non-web hosted scenarios and took us a step a closer.

Now in 2019 with the release of .NET core 3.0 we have finally converged on a unified HostBuilder that supports both web/non-web hosted applications!

Generic Host - Console Application

Here's an example of setting up a simple class for a non-web based application:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
               services.AddHostedService<HostedService>();
            });
}

Tip: The host builder expects a class be inherited from the IHostedService interface. It will call the StartAsync method on each Hosted Services registered in the ConfigureServices methods during the application startup.

Generic Host - Web Application

Here is an example of how to configure a web application using the Generic Host:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

The Startup class registered here will configure services and the web applications request pipeline.