4

I am confused right now, and maybe does not understand the real problem.

I have an object which require logger instance to log error data.

for example

public class CommonFileSaver : IFileSaver
    {
           private static ILog _log = LogManager.GetLogger();

           .....
    }

I wish to test the logging process. And my current decission is to use the mock of the ILog interface.

At this point I have decided to use Unity to resolve dependencies.

So the line

ILog _log = LogManager.GetLogger(); 

will look something like

ILog _log = Resolver.Instance.Resolve<ILoger>();

The question is how to setup the Unity container to return me new instance of the ILog object using LogManager factory.

Thank you.

P.S. ILog is the log4net interface, and the whole logging thing is implemented using log4net right now.

v00d00
  • 3,215
  • 3
  • 32
  • 43

4 Answers4

3

Maybe it is not correct in design, but using factory is possible in Unity...

_container = new UnityContainer();
_container.RegisterType<ILog>(new InjectionFactory(c => LogManager.GetLogger()));
v00d00
  • 3,215
  • 3
  • 32
  • 43
2

The problem here is that you're not following the Hollywood principle. Static factory methods and singletons don't fit well with dependency injection. You should change your code, to inject your ILog factory:

public class CommonFileSaver : IFileSaver
{
   public CommonFileSaver(ILogFactory logFactory)
   {
      _log = logFactory.GetLogger();
   } 

   private readonly ILog _log;

   .....
}
onof
  • 17,167
  • 7
  • 49
  • 85
1

You could write a wrapper for log4net (something which imho is a good idea anyway). The wrapper would take care of creating the instances by using the log4net factory method and it would also make sure that the "Configure" method is called.

If you write a wrapper you might want to consider this information.

Community
  • 1
  • 1
Stefan Egli
  • 17,398
  • 3
  • 54
  • 75
1

If the goal of what you are trying to achieve is to test the logging process with a mock ILog when I would suggest that you also mock the LogManager and set up an expectation on the GetLogger so that it will return the mock ILog.

Phil Carson
  • 884
  • 8
  • 18