Understanding CreateDefaultBuilder and Configuration Management in .NET/ASP.NET Core

CreateDefaultBuilder and Configuration Management in NETASPNET Core

In our last article, we already looked at how to manage App configuration in ASP.NET Core is based on key-value pairs.

We also looked at different Configuration providers to read configuration data into key-value pairs from a variety of configuration sources.

Today in this article we will see basic usage CreateDefaultBuilder which is a Host Builder with the additional ability of loading default configuration.

Today in this article, we will cover below aspects,

CreateDefaultBuilder a generic Host builder in .NET and ASP.NET Core plays an important role in initializing the Host and its configuration like getting access to applications host details including app configuration, logger configuration, user secretes, getting access to environmental configuration etc.

It Initializes a new instance of Microsoft.Extensions.Hosting.HostBuilder class with pre-configured defaults.

Host Builder using CreateDefaultBuilder works in ASP.NET Core and non-host apps like a Console application or WPF application as well.

Typical implementation of CreateWebHostBuilder looks as below,

ASP.NET Core

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();


Non-host Apps

 var builder = new HostBuilder()

Or

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

Let see in detail how CreateDefaultBuilder helps us managing all the above details.

Access to Application Configuration in ASP.NET and NET Core

Please note that when you define your host with CreateDefaultBuilder it loads Application Configuration in ASP.NET Core appsettings.json in ASP.NET Core.

This application configuration is available to you out of the box and accessible through the IConfiguration interface.

If you are using a non-prod environment like DEV or TEST then such environment-specific configuration details will also be available from appsettings.[EnvironmentName].json

Example:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ServerURL": "https://localhost:44347/api/employee",
  "ConnectionStrings": {
    "EmployeeDB": "Server=localhost\\SQL;Database=master;Trusted_Connection=True;"
  }
}

CreateDefaultBuilder and Configuration Management in NETASPNET Core

Access to Logger Configuration in ASP.NET and .NET Core

If you have any logger configuration defined in the Application Configuration file like appsettings.json or appsettings.[EnvironmentName].json then such configuration gets loaded and associated with logger instance created or enabled by you.

Generally, a type of logger mostly gets decided using a declarative approach where the user can specify the Console or File logger. Then configuration defined in the setting can be used for specifying the log level.

Here is an example,

Let’s use the below log configuration,

"Logging": {
    "LogLevel": {
      "Default": "Information",
    }

Here is sample code,

 internal void Run()
        {

            _logger.LogInformation("Logging Information");
            _logger.LogError("Logging Error");
            _logger.LogWarning("Logging Warning");
            _logger.LogInformation(_baseURL);
            _logger.LogDebug("Logging Debug");
        }

Below are the logs created,

CreateDefaultBuilder and Configuration Management in NETASPNET Core

If the configuration changed to ‘Warning‘ recommended in the PROD environment then for the above example, it shall show only warn and fail message only.

CreateDefaultBuilder will also log to Console, Debug, EventSource and EventLog(in Windows machine) as we discussed in the article Logging in ASP.NET Core.

Access to LoggerFactory Configuration in ASP.NET and .NET Core

LoggerFactory instance if any in the application will be enabled with logger configuration defined in the Application Configuration file like appsettings.json or appsettings.[EnvironmentName].json.

So basically ILoggerFactory will log to the console, debug, and event source output.

Access to Environment Configuration in ASP.NET and .NET Core

CreateDefaultBuilder and Configuration Management in NETASPNET Core

So far all the above-discussed configuration, you get by initializing your HostBuilder as below using CreateDefaultBuilder. With this ideally you don’t need to load any of the above configurations using any custom providers (if default configuration loaded through default builder works and suffices to your requirement)

ASP.NET Core

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

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

.NET Core IoC container (For Console and Win Form or WPF)

                var hostBuilder = Host.CreateDefaultBuilder()

                .ConfigureServices((hostContext, services) =>
                {
                    //Add you business services

                }).Build();

References :

That’s all, Happy Coding

Summary

Today in this article we saw usage CreateDefaultBuilder a generic Host builder in .NET and ASP.NET Core. We looked at how it helps us to provide access application configuration, user secretes, getting access to environmental information, etc out of the box. It works fine with many other custom configuration providers as well (like JSON, XML, INI etc.) providing greater flexibility in managing the configuration data.



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 *