Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject.Extensions.Logging.nlog2 - How to?

Browsing the nuget library, i came across Ninject.Extensions.Logging.nlog2. Some googling and trying to figure things out, I can't seem to find how or why you would use this extension.

Is it advisable to use with MVC 3?

What exactly is the point?

How do you use it?

like image 657
Erik Funkenbusch Avatar asked Aug 17 '11 01:08

Erik Funkenbusch


1 Answers

It's really very simple; both NLog and log4net expect you to use singleton/static references to obtain logger instances:

private static Logger logger = LogManager.GetCurrentClassLogger();

This is widely considered to be an anti-pattern, but even if you have no problem with it, it's still going against the grain if you're trying to implement dependency injection. In the case of NLog it's not even an ILog or ILogger interface like log4net, it's an actual class. That carries certain disadvantages such as the inability to create proxies, deferred loading, caching, etc.

What the Ninject.Extensions.Logging project does is first provide an abstract ILogger class with simple methods like Info, Error, etc., so you can inject it as a dependency and switch the logging framework if you want:

public class WidgetProvider
{
    private readonly ILogger log;

    public WidgetProvider(ILogger log)
    {
        this.log = log;
    }
}

This is how DI is supposed to work - a class never goes out to grab its own dependencies, instead they're supplied by the constructor or caller as above. Assuming you've already integrated Ninject itself into your project, that's really all you have to do, there is no additional work.

As for what Ninject.Extensions.Logging.NLog2 does specifically - it just provides an implementation for Ninject.Extensions.Logging based on NLog2. The base Logging library doesn't actually contain any implementations of ILogger, you have to plug in one of the specific libraries (NLog, NLog2, or log4net) in order to get it to work.

If you switch your DI library more often than you switch loggers then don't bother with it. But if you're like me and use Ninject in almost every project, then it's a nice way to decouple your code from any specific logging library.

like image 60
Aaronaught Avatar answered Sep 21 '22 07:09

Aaronaught