18

.Net Core Console DI, HttpClientFactory and Serilog

 4 years ago
source link: https://www.aligneddev.net/blog/2019/dotnet-core-console-di-and-serilog/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.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();
        }
    }
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK