dagger
dagger copied to clipboard
Support method injection.
Sometimes you want to execute code after all the injections have taken place and Constructor injection won't work well ( building a class meant for subclassing, etc ).
It would be nice to have a callback after the injection has completed:
@OnInjectionCompleted public void mySetup(){ }
If you aren't using constructor injection can't you just do this yourself?
That is a bit complicated to do since if we requires an init method to be called, that means all the class's dependents needs to call it before the object becomes usable — breaking the DI/IoC principle.
We could use the factory pattern, but that is combersome/complicated and is the reason why we're using dagger in the first place. And constructor injection has its own set of inconveniences as the OP said. @Provider mode also doesn't scale well once you have a number of classes in your projects that needs some kind of initialization.
jsr250 has a postconstruct annotation. From my own experience, if you need an after constructor 'callback' when doing DI, your design is broken, but I realize those things are unfortunately rather the norm than the exception.
When doing DI, you usually first build the graph before doing business. Introducing a postconstruct callback breaks this flow as it encourages to do business while the graph is being build.
The main reason for this (at least for me) is that constructor injection is cumbersome (as if Java wasn't cumbersome enough already). Using constructor injections would of course be more "unbroken" but that means we have to save all the dependency references (final vars or what have you) and repeat a ton of pointless this.a = a code. That is why I prefer property injections over ctor injection. It is basically much more straightforward and practical. But that means I then lose the ability to do after-injection initialization should there be any need to. Thus this issue.
IMO Constructors in languages like Java should be kept as simple as possible. There is a good reason why almost all the important Android classes are designed such that you can't construct them directly yet there is almost always a well-defined way add initialization code should you need to (callba.. ahem onCreate() and friends)
There is a good reason why almost all the important Android classes are designed such that you can't construct them directly
The "good reason" is that they eschew any ounce of proper API design for eliminating every shred of overhead. Even that is a mostly a function of legacy nowadays.