What is the convention when I have dependencies which are optional, like for example logging ? I want to have them injected by properties. And what after when nobody set it? Check for null every time ? Or get a fake logger which does nothing ? 1.The problem is not related only for logging. 2. I am asking for convention when injecting via properties.
Asked
Active
Viewed 1,265 times
2
-
1Your design is flawed. Dependencies should never be "optional". Can you provide a more solid use case for your scenario? – Simon Whitehead Dec 02 '13 at 10:17
-
That's interesting. So how should look like logger when I don't want to log when running unit tests? I use log4net – MistyK Dec 02 '13 at 10:25
-
What if I write library which includes logging. As I read, convention is to inject it via constructor, but I don't want user to have it necessary, that's why I inject it via properties. Logging is addition, not main functionality. Why can't be optional ? – MistyK Dec 02 '13 at 10:29
-
How about having a flag whether to log or not? – Imran Dec 02 '13 at 10:36
-
Imran, checking that flag every time when I want to use it this object is the same as checking for null – MistyK Dec 02 '13 at 10:37
-
If Unit Testing is your concern with this.. you should be aware that Mocking frameworks exist for this very purpose.. – Simon Whitehead Dec 02 '13 at 11:02
-
Yeah I know it. But what if someone forget to inject that logger mock ? Will get null reference exception. My job is to prevent situations like this, am I not right? – MistyK Dec 02 '13 at 11:06
-
I think it would be better to centralize all the logging calls to a method say "Log(...)" and you can do the stuff like null check or flag check like IsLoggingRequired in this method. – Imran Dec 02 '13 at 11:49
-
I made an extension method for method "Log" which checked for null, but now I just made class FakeLogger which does nothing. It implements ILog interface. It's working but don't know if it's best solution – MistyK Dec 02 '13 at 11:55
-
http://stackoverflow.com/questions/17613795/logging-and-dependency-injection – jaco0646 Dec 03 '13 at 03:31
1 Answers
1
Property injection is typically used when you can generally rely on a default implementation but want the option of injecting an alternative.
In your example, you might create a DefaultLogger that the class uses unless someone passes in an alternative via a property.
I think there should always be an instance of something, a 'null object' maybe. Checking for null doesn't feel right.
Also, have you considered decoration? Logging is a great example of how decoration can add extra, optional, features.

David Osborne
- 6,436
- 1
- 21
- 35