Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 637
Stackedup Avatar asked Sep 20 '25 05:09

Stackedup


2 Answers

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.

like image 183
mjwills Avatar answered Sep 23 '25 12:09

mjwills


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");
    }
}
like image 40
Shijie Zhang Avatar answered Sep 23 '25 13:09

Shijie Zhang