Skip to content
C1aud3 edited this page Feb 22, 2017 · 7 revisions

When using the logging extension, you can have the logger injected in a number of ways

Injected through the constructor

using Ninject.Extensions.Logging;

public class CtorPropertyLoggerClass
{
    public CtorPropertyLoggerClass( ILogger logger )
    {
        Logger = logger;
    }

    public ILogger Logger { get; private set; }
}

Injected into a property

public class PublicPropertyLoggerClass
{
    [Inject]
    public ILogger Logger { get; set; }
}

Request a logger yourself

ILoggerFactory loggerFactory = kernel.Get<ILoggerFactory>();
ILogger logger = loggerFactory.GetCurrentClassLogger();
ILogger logger = loggerFactory.GetLogger( MethodBase.GetCurrentMethod().DeclaringType );
ILogger logger = loggerFactory.GetLogger( GetType() );

In order to setup logging, you just need to declare the logger in your class according to how you want it injected, and make sure you have the kernel load a new Log4NetModule or NLogModule before requesting the type instance.

public abstract class CommonTests : ILoggingTestContext
{
    [Fact]
    public void PublicLoggerPropertyIsInjected()
    {
        using ( var kernel = CreateKernel() )
        {
            var loggerClass = kernel.Get<PublicPropertyLoggerClass>();
            Assert.NotNull( loggerClass.Logger );
            Assert.Equal( typeof (PublicPropertyLoggerClass), loggerClass.Logger.Type );
            Assert.Equal( LoggerType, loggerClass.Logger.GetType() );
        }
    }

    [Fact]
    public void NonPublicLoggerPropertyIsNotInjected()
    {
        using ( var kernel = CreateKernel() )
        {
            var loggerClass = kernel.Get<NonPublicPropertyLoggerClass>();
            Assert.Null( loggerClass.Logger );
        }
    }

    [Fact]
    public void CtorLoggerPropertyIsInjected()
    {
        using ( var kernel = CreateKernel() )
        {
            var loggerClass = kernel.Get<CtorPropertyLoggerClass>();
            Assert.NotNull( loggerClass.Logger );
            Assert.Equal( typeof (CtorPropertyLoggerClass), loggerClass.Logger.Type );
            Assert.Equal( LoggerType, loggerClass.Logger.GetType() );
        }
    }

    protected virtual IKernel CreateKernel()
    {
        var settings = CreateSettings();
        return new StandardKernel( settings, new Log4NetModule(), TestModule );
    }

    protected virtual INinjectSettings CreateSettings()
    {
        var settings = new NinjectSettings();
        settings.LoadExtensions = false;
        return settings;
    }

    public abstract INinjectModule TestModule { get; }
    public abstract Type LoggerType { get; }
}
Clone this wiki locally