Search code examples
c#model-view-controllerautofacnlog

How to use NLog in static class where everything else is wired with Autofac


My MVC app is wired with Autofac. I have also configured NLog which works as expected in my controller classes. My nLogger is registered as below:

var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(LoggerService<>))
  .As(typeof(ILoggerService<>)).SingleInstance();
var container = builder.Build();

And the constructor of the ILoggerService is:

public LoggerService()
{
    SourceClass = typeof (T).FullName;
    Logger = LogManager.GetLogger(SourceClass);
 }

Now I have also got many static helper classes that I use. For example:

public static class Helper
{
   public static string GenerateQrBitmap(string secret, string issuer, string userEmail)
   {
     ...
   }
}

But I want to be able to use the logger in these Helper classes as well.


Solution

  • This is one of the reasons why static classes aren't great.

    You have two options:

    1. Make them not static (and register them with Autofac) and take ILoggerService as a constructor parameter.
    2. Change their methods (e.g. GenerateQrBitmap) to take a ILoggerService as a parameter.

    I'd suggest the former.

    The alternative is to use the Service Locator pattern - and have Helper resolve directly against the container. I will not show you how to do this, since I don't recommend it. It makes the code harder to unit test, and it hides your dependencies. But if you Google Autofac Service Locator static class c# I'm sure you'll work it out.