1
votes

I am using the excellent LibLog code for abstracting logger implementation in my application.

I am also using Simple Injector as my DI container.

I would like to inject an instance of logger in my classes which corresponds to the following static creation

private readonly ILog logger = LogProvider.For<MyClass>()

or if you like the static method

private readonly ILog logger = LogProvider.GetCurrentClassLogger()

Is it correct to do it this way?

container.Register<ILog>(() => LogProvider.GetCurrentClassLogger(), Lifestyle.Singleton);

Or there is a better way ?

Edit:

  <package id="SimpleInjector" version="4.0.8" targetFramework="net461" />
  <package id="SimpleInjector.Packaging" version="4.0.8" targetFramework="net461" />
1
My kingdom for "using" namespaces. (If you get a chance to list them, that would be great. Also "packages.config" to show the versions you're using when asking the question. - granadaCoder
Hello, I am not sure I’ve got your question. If you mean namespaces of ILog interface as well as LogProvider class, then please have a look at the first link in the question, the one for the LibLog nuget. LibLog is a nuget that provide you with the source code so the namespace is of your project, I’ve added SimpleInjector versions. If I’m wrong, can you please let me better understand? - Lorenzo
Yeah, I see it now. This is the first time i've seen a nuget package bring in source-code......and not a precompiled assemby. A little weird, but I "see" it now. Thx. - granadaCoder

1 Answers

1
votes

Registering LogLib is idential to how to register log4net and to register nlog with Simple Injector, and the documentation explains this as well here.

You need to make a conditional registration for ILog as follows:

container.RegisterConditional(typeof(ILog), 
    context => typeof(LibLogLog<>).MakeGenericType(context.Consumer.ImplementationType), 
    Lifestyle.Singleton, 
    context => true);

LibLogLog<T> is a generic class that forwards the call to LogProvider.For<T>():

public sealed class LibLogLog<T> : ILog
{
    private static readonly ILog logger = LogProvider.For<T>();
    public bool Log(LogLevel l, Func<string> f, Exception e, params object[] p) =>
        logger.Log(l, f, e, p);
}

LibLog is actually one of the few logging libraries that designed their log interface correctly (i.e. with just one member). This makes it trivial to implement this LibLogLog<T> proxy.