Hari
Hari

Reputation: 4612

How to get implementing type during Ninject dependency resolve?

I use Log4net for logging and I have a lot of objects with an ILog dependency. These dependencies are injected just as the others. I would like to stick to the Log4net logger naming convention so the logger injected to an instance is named after the type of the instance. I have been using the following binding for ILog:

Bind<ILog>().ToMethod(ctx =>
    LogManager.GetLogger(ctx.Request.ParentRequest == null ? typeof(object) : ctx.Request.ParentRequest.Service)
);

Which is against the naming convention because loggers will be named after the interface not the implementing type.

interface IMagic {}

class Magic: IMagic
{
    ILog logger; // The logger injected here should have the name "Magic" instead of IMagic
}

I tried a couple of ways to get the implementing type from ctx with no success. Is there any way to get the implementing type?

Upvotes: 0

Views: 654

Answers (1)

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13233

this and that covers your questions but they're not exactly duplicates, so i'll repost this:

Bind<ILog>().ToMethod(context =>
             LogManager.GetLogger(context.Request.ParentContext.Plan.Type));

so context.Request.ParentContext.Plan.Type is the type ILog is injected into. If you ever want to do IResolutionRoot.Get<ILog>() then there won't be a type to inject ILog into and so there won't be a ParentContext either. In that case you'll need the null check as in your previous solution:

Bind<ILog>().ToMethod(context =>
             LogManager.GetLogger(context.Request.ParentContext == null ?
                                  typeof(object) : 
                                  context.Request.ParentContext.Plan.Type));

Upvotes: 4

Related Questions