Do not shoot the messenger.
I was recently asked this question and I sort of stumbled on the response. So I’m posting it here. Please respect the legitimacy of it.
If I can
property name=“injector” inject=“wirebox”
into all my service classes, why do I need to inject anything else at all, when I can just getInstance("") what I need from my “injector” reference?
There’s absolutely nothing keeping you from doing that
The reasons i choose not to do it for singletons are:
- myservice.foo() is less code than injector.getInstance( “myService” ).foo()
- DSLs are even MORE code since you have to do getInstance( dsl=“logbox:logger:foo” )
- mixins are only injected once so there’s no wirebox overhead every time you need it (not that it’s really much though)
- I like having nice documentation right at the top of the component as to what dependencies it needs which helps when refactoring
I should also mention that in some instances you NEED to take that approach. For instance, if you need to create a throw-away instance of a transient object, you wouldn’t want to inject it but rather ask WireBox for it every time. The same goes for session, request, cachebox, etc scoped objects.
ColdBox Platform Evangelist
Ortus Solutions, Corp
ColdBox Platform: http://www.coldbox.org
I agree with @Brad. I try to keep things at the top, but not if it is
something that is only used in 1 of 20 functions. But if it is used in most
functions, it is definitely something worth declaring. For access to
session, cgi, and other globals, we don't declare those at the top.