Ninject typeof pass constructor argument of a class that implements an interface

I am trying to use Ninject with an application registration shell.

Here is a wrapper:

public class NLogLogger : ILogger { private readonly Logger _logger; public NLogLogger(Type t) { _logger = LogManager.GetLogger(t.Name); } } 

As you can see, I pass this type to the logger constrctor, so I would use it as shown below:

 public class EntityObject { public ILogger Logger { get; set; } public EntityObject() { Logger = new NLogLogger(typeof(EntityObject)); } } 

Now I cannot figure out how to do something like this using Ninject. Here is my binding module:

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

Now, obviously, I am getting an exception because it cannot inject a type into the constructor. Any ideas how I can do this?

Error activating type

There are no matching bindings, and the type is not self-switching.

Activation path:

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

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

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

1) DashboardController request

+2
c # inversion-of-control ninject
source share
1 answer

Assuming 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 will need to register your NLogLogger as follows:

 Bind<ILogger>().To<NLogLogger>() .WithConstructorArgument( typeof(Type), x => x.Request.ParentContext.Plan.Type); 
+2
source share

All Articles