How to create a standalone ConsoleLoggerProvider

By Mike Hadlow, published Jul 27, 2021

If, for whatever reason you want to create a stand alone instance of ConsoleLoggerProvider without having to leverage dependency injection and the full Hosting framework, you’ll find that the ConsoleLoggerProvider’s constructor requires an instance of an IOptionsMonitor<T>, the only instance of which OptionsMonitor<T> in turn has a complex constructor with many dependencies. This all seems like a failure of design on Microsoft’s part. Here I give a simple no-op IOptionsMonitor<T> implementation to allow one to easily create a ConsoleLoggerProvider.

using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
using System;

namespace Sample
{
    class Program
    {
        static void Main()
        {
            var loggerProvider = new ConsoleLoggerProvider(new OptionsMonitor<ConsoleLoggerOptions>(new ConsoleLoggerOptions()));
            // use the loggerProvider ...
        }
    }

    public class OptionsMonitor<T> : IOptionsMonitor<T>
    {
        private readonly T options;

        public OptionsMonitor(T options)
        {
            this.options = options;
        }

        public T CurrentValue => options;

        public T Get(string name) => options;

        public IDisposable OnChange(Action<T, string> listener) => new NullDisposable();

        private class NullDisposable : IDisposable
        {
            public void Dispose() { }
        }
    }
}

Hi, I’m Mike Hadlow. Software developer, architect, blogger and open source developer.

Find my old blog at Code Rant. This ran from 2005 to 2020 and has hundreds of posts.

All code on this blog is published under an MIT licence. You are free to copy it and use it for any purpose without attribution. There is no warranty whatsoever.

There are no cookies on this site

The GitHub repository for this site is here.