Binding Ninject to an instance based upon the dependency type

I want to bind the Common.Logging.ILog to an implementation which can take a type argument as it’s parameter, i.e. We can use the Common.Logging.LogManager.GetManager method by passing a type into it, as per the following code

LogManager.GetLogger(typeof(MyType));

So how can we simply declare a dependency on our type to ILog and have it automatically get the logger with the type parameter.

The code speaks for itself, so here it is

IKernel kernel = new StandardKernel();

kernel.Bind<ILog>().ToMethod(ctx =>
{
   Type type = ctx.Request.ParentContext.Request.Service;
   return LogManager.GetLogger(type);
});

In the above code we bind to a method, thus we can dynamically handle the binding. From the IContext ctx we can find which type requested the binding and then use this in the call to GetLogger.

So with this the dependency object simply includes the following

public class MyClass
{
   // other methods, properties etc.

   [Inject]
   public ILog Logger { get; set; }
}

and everything “magically” binds together to get the logger with the type set to typeof(MyClass).