Ninject pass constructor argument typeof class that implements the interface
Asked Answered
E

1

2

I am attempting to use Ninject with my application logging wrapper.

Here is the wrapper:

public class NLogLogger : ILogger
{
    private readonly Logger _logger;

    public NLogLogger(Type t)
    {
        _logger = LogManager.GetLogger(t.Name);
    }
}

As you can see I am passing the type into the loggers constrctor, so I would use it like the following:

public class EntityObject
{
    public ILogger Logger { get; set; }

    public EntityObject()
    {
        Logger = new NLogLogger(typeof(EntityObject));
    }
}

Now I cannot seem to find out how to do something similar with using Ninject. Here is my binding module:

public class LoggerModule : NinjectModule
{
    public override void Load()
    {
        Bind<ILogger>().To<NLogLogger>();
    }
}

Now obviously I get an exception thrown because it cannot inject the type into the constructor. Any ideas how I can do this?

Error activating Type

No matching bindings are available, and the type is not self-bindable.

Activation path:

4) Injection of dependency Type into parameter t of constructor of type NLogLogger

3) Injection of dependency ILogger into parameter logger of constructor of type NzbGetSettingsService

2) Injection of dependency ISettingsService{NzbGetSettingsDto} into parameter nzbGetService of constructor of type DashboardController

1) Request for DashboardController

Explain answered 18/11, 2015 at 21:33 Comment(0)
B
2

Assuming that your classes look like this:

public class EntityObject
{
    public ILogger Logger { get; set; } //it is better by the way to convert this into a private field

    public EntityObject(ILogger logger)
    {
        Logger = logger;
    }
}

You would need to register your NLogLogger like this:

Bind<ILogger>().To<NLogLogger>()
    .WithConstructorArgument(
        typeof(Type),
        x => x.Request.ParentContext.Plan.Type);
Baluster answered 18/11, 2015 at 22:4 Comment(1)
Awesome, thank you. I've been pulling my hair out about this one!Explain

© 2022 - 2024 — McMap. All rights reserved.