Search code examples
inversion-of-controllog4netstructuremap

Using structuremap with log4net wrapper


I have the following interface:

    public interface ILogger
    {
        void Debug(string message, params object[] values);
        void Info(string message, params object[] values);
        void Warn(string message, params object[] values);
        void Error(string message, params object[] values);
        void Fatal(string message, params object[] values);
    }

and the following implementation:

    public class Log4netLogger : ILogger
    {
        private ILog _log;

        public Log4netLogger(Type type)
        {
            _log = LogManager.GetLogger(type);
        }

        public void Debug(string message, params object[] values)
        {
            _log.DebugFormat(message, values);
        }

        // other logging methods here...

    }

My idea was to use structuremap to instantiate the Log4netLogger class with using the Type of the class that did the logging. However, I can't for the life of me figure out how to pass the type of the calling class to structuremap so that it can be passed to the constructor of the logging implementation. Any advice on how to do that (or a better way) would be most appreciated.


Solution

  • If the type parameter is context-specific, I don't think this is going to work as shown. If you need to pass something context specific in the constructor, you are likely going to have to create a factory interface and implementation that returns an instance of the ILogger:

        public interface ILoggerFactory
        {
            ILogger Create(Type type);   
        }
        
        public class LoggerFactory : ILoggerFactory
        {
            public ILogger Create(Type type)
            {
                return new Log4netLogger(type);
            }
        }
    

    It might be possible to bootstrap StructureMap to supply the instance you want based on the type, but that assumes a limited number of types that you know in advance.