Building NetCore Console Application with Logging and Dependency Injection

Share this post

In this article, we will create a simple console application with .Net dependency Injection and Serilog.

Create a Dotnet console application, either using CLI or IDE. this should generate a default minimal code similar to the following:

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

We will be using dotNet DI to load and inject services into the application. To do so, we need to create a host for the services, load any configuration needed, and configure the various services.

Since we will be using Serilog as our logger, add the following NuGet packages to the applications:

  • Serilog
  • Serilog.Extensions.Hosting
  • Serilog.Settings.Configuration
  • Serilog.Sinks.Console

Create a method to set the basic folder part and load default configurations:

static void BuildConfig(IConfigurationBuilder builder) {
    builder.SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .AddEnvironmentVariables();
}

Next, we need to create a method to create and initialize the application host, with it’s services. Since we will be using Serilog for logging, this is the place to create a Serilog logger and add it to the application host.

tatic IHost CreateApplicationHost() {
  var builder = new ConfigurationBuilder();
  BuildConfig(builder);

  // Specifying the configuration for serilog
  Log.Logger = new LoggerConfiguration() // initiate the logger configuration
    .MinimumLevel.Debug()
    .Enrich.FromLogContext() //Adds more information to our logs from built in Serilog 
    .WriteTo.Console() // Output the logs to the console
    .CreateLogger();

  var host = Host.CreateDefaultBuilder() // Initialising the Host 
    .ConfigureServices((context, services) => {
      // Adding the DI container for configuration
    })
    .UseSerilog() // Add Serilog
    .Build(); // Build the Host

  return host;
}

Update the Main() method to use CreateApplicationHost to create the host:

public static async Task Main(string[] args)
{
    var host = CreateApplicationHost();
}

Next, we will create a sample service that implements a very basic interface :

public interface IHello
    {
        void Greet();
    }

And the service implementation:

public class HelloService : IHello
    {
        private readonly ILogger _logger;

        public HelloService(ILogger<HelloService> logger)
        {
            _logger = logger;
        }
        
        public void Greet()
        {
            _logger.LogInformation("Hello world");
        }
    }

Now, we need to configure the application service collection, and add HelloService:

services.AddTransient();

Finally, we can use it from the Main() method:

static void Main(string[] args)
    {
        var host = CreateApplicationHost();

        var greeter = host.Services.GetRequiredService<IHello>();
        greeter.Greet();
    }

And that’s it!

Thanks for reading and happy coding 🙂

Article cover image by Wälz from Pixabay