Hooman Bahreini
Hooman Bahreini

Reputation: 15579

Ninject, how inject a generic Logger<T> by calling LoggerFactory.CreateLogger

I am working on an ASP.NET MVC application.

I have initialized my LoggerFactory in a static class which is called from Global.asax

using Microsoft.Extensions.Logging;
using Serilog;
using System.IO;

namespace web
{
    public static class LogConfig
    {
        public static LoggerFactory LoggerFactory = new LoggerFactory();

        public static void RegisterLogger()
        {
            LoggerFactory = new LoggerFactory();
            Log.Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.RollingFile(Path.Combine("", "log-{Date}.txt")).CreateLogger();
            LoggerFactory.AddSerilog();
        }
    }
}

now I want to use ninject, to inject an instance of ILogger into my constructor...

In my constructor I have:

private ILogger<MyTypeController> _logger;

public MyTypeController(ILogger<MyTypeController>) 
{
    // This works fine but I want to inject it
    _logger = LogConfig.LoggerFactory.CreateLogger<MyTypeController>();
}

The above code works, but I want to inject it using ninject... this is what I have tried but does not even compile:

kernel.Bind(typeof(ILogger<>)).ToProvider(LogConfig.LoggerFactory.CreateLogger<>());

Upvotes: 4

Views: 4691

Answers (3)

David C.
David C.

Reputation: 48

very simple solution:

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Ninject;

// ...
// register log factory, in case of serilog:
kernel.Bind<ILoggerFactory>().To<SerilogLoggerFactory>();

// register generic ILogger<T>
kernel.Bind(typeof(ILogger<>)).To(typeof(Logger<>));

Upvotes: 0

Hooman Bahreini
Hooman Bahreini

Reputation: 15579

Reading the comments given by @Steven and also reading his blog on Simple Injector, I have realized that injecting a generic logger ILogger<T> is not really a good approach.

See this answer for more details.

Upvotes: 0

oeaoaueaa
oeaoaueaa

Reputation: 91

I'm doing the following with NLog but it is also likely to work with Ninject:

var createLoggerMethod =
    typeof(LoggerFactoryExtensions).GetMethod(nameof(LoggerFactoryExtensions.CreateLogger),
        new[] {typeof(ILoggerFactory)});
kernel.Bind(typeof(ILogger<>)).ToMethod(context =>
{
    var createLoggerGeneric = createLoggerMethod.MakeGenericMethod(context.GenericArguments);
    var logger = createLoggerGeneric.Invoke(null, new []{ loggerFactory });
    return logger;
});

Upvotes: 9

Related Questions