Which pattern to use for logging? Dependency Injection or Service Locator?
Posted
by andlju
on Stack Overflow
See other posts from Stack Overflow
or by andlju
Published on 2010-04-21T11:48:07Z
Indexed on
2010/04/21
12:53 UTC
Read the original article
Hit count: 206
Consider this scenario. I have some business logic that now and then will be required to write to a log.
interface ILogger
{
void Log(string stuff);
}
interface IDependency
{
string GetInfo();
}
class MyBusinessObject
{
private IDependency _dependency;
public MyBusinessObject(IDependency dependency)
{
_dependency = dependency;
}
public string DoSomething(string input)
{
// Process input
var info = _dependency.GetInfo();
var intermediateResult = PerformInterestingStuff(input, info);
if (intermediateResult== "SomethingWeNeedToLog")
{
// How do I get to the ILogger-interface?
}
var result = PerformSomethingElse(intermediateResult);
return result;
}
}
How would you get the ILogger interface? I see two main possibilities;
- Pass it using Dependency Injection on the constructor.
- Get it via a singleton Service Locator.
Which method would you prefer, and why? Or is there an even better pattern?
Update: Note that I don't need to log ALL method calls. I only want to log a few (rare) events that may or may not occur within my method.
© Stack Overflow or respective owner