I have been investigating ways to inject the Log4Net ILog into classes using Castle Windsor. In most examples, I see where Castle Windsor can provide a "facilitator" that provides property injection, and injects the ILogger (not ILog). I have found only one example where contructor injection is used, and the facilitator method is not used (see Castle Windsor dependency injection: Use the caller type as a parameter)
In all these examples, it seems Log4Net wants to have a named logger. Most examples refer to the Log4Net static method LogManager.GetLogger(class name here). This makes it a challenge to define the dependancies for CastleWindsor without using reflection, or the facilitator method (can facilitator method be used with ctor injection???). When looking at the question by Ilya Kogan (URL above...), I guess I don't understand why I need, or even want a named logger. Can't I use a logger by the same name everywhere?
For example, can't I just register the logger with hardcoded name of XXX? (It seems to work fine, and in the end, I just want to log - I don't care which logger logged it...) Is there a scope issue? Is there a memory leak issue? Why can't/shouldn't the logger be a singleton?
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<log4net.ILog>().UsingFactoryMethod(() => log4net.LogManager.GetLogger("xxx"))
);
}
UPDATE:
Upon some research, a hardcoded named logger can be used - such as XXX in my example above, but if the configuration of the logger outputs the logger name to the logfile and if the logger name is dynamically assigned to the same name as the method or class, you automagically get reference to where the logging originated from. Context within the log file can be very helpful.
When specifically addressing ctor injection, there seems to be 5 possible options...
- Use a singleton and not use named loggers (thus not reported in log file)
- Use reflection with ctor injection (as seen in Ilya Kogan's example)
- Use property injection (via facilitators)
- Use post-sharp AOP IL Injection for logging
- Use CTOR injection (via facilitators)