.Net Core Console DI, HttpClientFactory and Serilog

October 31, 2019    Development .Net Core .Net

.Net Core Console DI, HttpClientFactory and Serilog

I needed to create a .Net Core 3.0 console app that makes HTTP calls and log results to a text file. It took me awhile and I used a few resources, so I’m creating this article for future reference.

Andrew Luck has good details on setting up DI in a console app as usual. I keep finding his articles when searching.

I learned about logging and dependency injection from Emanuel Paul .

For Serilog Logging I visited the docs and an article about .Net Core, DI and Serilog

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

namespace MyConsoleApp
{
    class Program
    {
        private static IConfigurationRoot _config;
        private static Settings _settings;

        static async Task Main(string[] args)
        {
            _config = ConfigurationHelper.GetIConfigurationRoot();
            var serviceProvider = RegisterServices();

            // configure console logging
            var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
            var myHttpClient = serviceProvider.GetService<IMyHttpClient>();
            PopulateFromSettings();

            await RunTestsAsync(myHttpClient, logger);
            serviceProvider.Dispose();
        }

        private static void PopulateFromSettings()
        {
            _settings = new Settings
            {
                MyUrl = _config["MyUrl"]
            };
        }

        private static ServiceProvider RegisterServices()
        {
            var configuration = SetupConfiguration();
            var serviceCollection = new ServiceCollection();

            var loggerConfiguration = new LoggerConfiguration()
                .WriteTo.File("TestRun.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .MinimumLevel.Information()
                .CreateLogger();
            serviceCollection.AddLogging(cfg =>
            {
                cfg.AddSerilog(loggerConfiguration);
            });

            serviceCollection.AddSingleton(configuration);
            serviceCollection.AddHttpClient<IMyHttpClient, myHttpClient>(client =>
            {
                client.BaseAddress = new Uri(_config["MyUrl"]);
                client.Timeout = TimeSpan.FromMinutes(1);
            })
            .ConfigureHttpMessageHandlerBuilder(builder =>
            {
                // ignore SSL issues
                builder.PrimaryHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (m, c, ch, e) => true
                };
            });
            return serviceCollection.BuildServiceProvider();
        }

        private static IConfiguration SetupConfiguration()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                //.AddEnvironmentVariables()
                //.AddCommandLine(args)
                .Build();
        }
    }
}


Watch the Story for Good News
I gladly accept BTC Lightning Network tips at [email protected]

Please consider using Brave and adding me to your BAT payment ledger. Then you won't have to see ads! (when I get to $100 in Google Ads for a payout (I'm at $95.73!), I pledge to turn off ads)

Use Brave

Also check out my Resources Page for referrals that would help me.


Swan logo
Use Swan Bitcoin to onramp with low fees and automatic daily cost averaging and get $10 in BTC when you sign up.