Adding Microsoft.Extensions to .NET Framework Application.

I have seen some pretty nice code in the .NET Core/.NET 5.x github and one of the things that interests me most currently is the extendable framework code.

All reasonably complex applications make use of supporting assemblies these days with dependency injection, logging, composition containers, configuration files, and complex command line processing being a few of the requirements for a large console application.

Every developer has their own preferred solution for these challenges and often that preference changes with time or tech leads. .NET core seems to have a good solution by abstracting the implementation behind a generalised interface. The interface is designed to be extendable and can be implemented by any concrete solution. In short, they have gone S.O.L.I.D.

I was initially stimulated to read up on this when I decided to replace log4net in one of my applications with Serilog because I could see some value in structured logging. There are some other potential gains too but I want to avoid a flame war so let’s just say I was interested…

I intend to create a series of posts on the topic but the starting point will be a simple console application with no extensions. It is just a plain old C# console application targeting .NET Framework 4.8. When you run it the command line is written to the console as a comma separated list.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Demo.Microsoft.Extensions.CLI
{
    internal class Program
    {
        private static async Task<int> Main(string[] args)
        {
            return await Task.Run(() => DefaultVerb(args));

        }

        /// <summary> Default verb. </summary>
        /// <remarks> This is a little action to use as a stub. </remarks>
        /// <param name="args"> The arguments. </param>
        /// <returns> An int. </returns>
        private static int DefaultVerb(IEnumerable<string> args)
        {
            var currentForeground = Console.ForegroundColor;
            try
            {
                Console.WriteLine(@"Default: Hello world!");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine($"Verb: Default called with {string.Join(",", args)}...");
                return 0;
            }
            finally
            {
                Console.ForegroundColor = currentForeground;
            }
        }
    }
}

I have uploaded that to github as v.0.0.0.alpha.1 in case you want to follow along.


Related Posts

  1. Add a JSON configuration

Published by badsoftwareday

A Software Engineer with more than 20 years experience

Leave a comment