How to set up a container unit to create scoffed / real magazine instances

I am confused right now and may not understand the real problem.

I have an object that requires a registrar instance to log error data.

eg

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

I want to check the logging process. And my current division is to use the ILog interface layout.

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

So the line

 ILog _log = LogManager.GetLogger(); 

will look something like this:

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

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

Thanks.

PS ILog is the log4net interface, and all logging is done using log4net right now.

+4
source share
4 answers

The problem is that you do not follow the principle of Hollywood. Static methods and singleton are not suitable for dependency injection. You must change your code to enter your ILog factory:

 public class CommonFileSaver : IFileSaver { public CommonFileSaver(ILogFactory logFactory) { _log = logFactory.GetLogger(); } private readonly ILog _log; ..... } 
+1
source

This may be wrong in design, but using factory is possible in Unity ...

 _container = new UnityContainer(); _container.RegisterType<ILog>(new InjectionFactory(c => LogManager.GetLogger())); 
+2
source

You can write a wrapper for log4net (something imho is a good idea anyway). The wrapper will take care of instantiating using the log4net factory method, and it will also make sure that the "Configure" method is called.

If you are writing a wrapper, you can consider this information .

+1
source

If the goal you are trying to achieve is to check the logging process with a false ILog, when I suggest you also mock LogManager and set the expected value to GetLogger so that it returns the ILog layout.

+1
source

Source: https://habr.com/ru/post/1337922/


All Articles