Stuck trying to get Log4Net to work with Dependency Injection

Posted by Pure.Krome on Stack Overflow See other posts from Stack Overflow or by Pure.Krome
Published on 2009-10-10T14:25:35Z Indexed on 2012/06/13 4:40 UTC
Read the original article Hit count: 216

I've got a simple winform test app i'm using to try some Log4Net Dependency Injection stuff.

I've made a simple interface in my Services project :-

public interface ILogging
{
    void Debug(string message);

    // snip the other's.
}

Then my concrete type will be using Log4Net...

public class Log4NetLogging : ILogging
{
    private static ILog Log4Net
    {
        get { return LogManager.GetLogger(
                       MethodBase.GetCurrentMethod().DeclaringType); }
    }

    public void Debug(string message)
    {
        if (Log4Net.IsDebugEnabled)
        {
            Log4Net.Debug(message);
        }
    }
}

So far so good. Nothing too hard there.

Now, in a different project (and therefore namesapce), I try and use this ...

public partial class Form1 : Form
{  
    public Form1()
    {
        FileInfo fileInfo = new FileInfo("Log4Net.config");
        log4net.Config.XmlConfigurator.Configure(fileInfo);
    }

    private void Foo()
    {
        // This would be handled with DI, but i've not set it up 
        // (on the constructor, in this code example).
        ILogging logging = new Log4NetLogging(); 
        logging.Debug("Test message");
    }
}

Ok .. also pretty simple. I've hardcoded the ILogging instance but that is usually dependency injected via the constructor. Anyways, when i check this line of code...

return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

the DeclaringType type value is of the Service namespace, not the type of the Form (ie. X.Y.Z.Form1) which actually called the method.

Without passing the type INTO method as another argument, is there anyway using reflection to figure out the real method that called it?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about reflection