Search code examples
loggingcastle-windsor

How to get to the requesting type in a Castle Windsor factory method?


I would like to use factory method during component registration to integrate static logger factory like this:

Component
    .For<ILogger>()
    .UsingFactoryMethod((kernel, componentModel, creationContext) => LoggingFactory.GetLogger("..."))
    .LifestyleTransient(),

GetLogger class expects the name of logging context. I would like to pass there full name of the class that requested logger. This would be unambiguous in this case as the lifestyle of ILogger service is transient.

I see that there is creationContext.RequestedType (that contains ILogger), but no creationContext.RequestingType.


Solution

  • You can get resolving type from creationContext.Handler.ComponentModel.Name. The following code should do what you need:

    Component
       .For<ILogger>()
       .UsingFactoryMethod((kernel, componentModel, creationContext) => LoggingFactory.GetLogger(creationContext.Handler.ComponentModel.Name))
       .LifestyleTransient(),