Stackedup
Stackedup

Reputation: 760

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.

Upvotes: 3

Views: 3935

Answers (2)

Shijie Zhang
Shijie Zhang

Reputation: 39

public static class TimeUtlis
{
    // When you want to use logger with specific class name
    static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    // When you want to use logger with fixed name
    static NLog.Logger UiLogger = NLog.LogManager.GetLogger("UI);

    public static string TimeTo24Hours(string time12Hours)
    {
        logger.LogError("you got it");
        UiLogger.LogError("brilliant solution");
    }
}

Upvotes: 0

mjwills
mjwills

Reputation: 23975

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.

Upvotes: 5

Related Questions