I have a Logging class which gets instantiated on startup of a console app and the stored in a static variable.

If i want a class to use the logger should it be passed to the class in the constructor or referenced directly?

I'm trying to write unit tests and either way i should be able to do it. Just means i have to set the static variable before calling the code that uses it.


No correct solution


Sounds like what you're looking for is some sort of IoC container. You could use EntLib's Unity or something else like that.

To make your classes as unit testable as possible, all dependencies, including loggers, should be passed in whenever possible. This is what is called Dependency Injection (DI), and is a very common and standard pattern for writing unit testable code. Logging is almost always a cross-cutting concern that is only embedded within the bodies of methods because there aren't really any decent AOP frameworks to properly pull those concerns out and apply them declaratively. Having to deal with logging when writing/running unit tests just increases the complexity of the tests, possibly adding additional configuration concerns, when you really want to keep your tests as simple and targeted as possible.

How about using the Static Gateway Pattern ?

You could create an instance of it and store that instance as a member of the same class & return that via a property.

e.g. Logger.Default
This will return the reference to the instance that was created.

EDIT: An example of this could be Console class & it's SetOut method. I mean you can keep on using Console.WriteLine.... and if you want to change the stream, use the SetOut method. It redirects the output to a new stream.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top