I'm just trying dagger instead of roboguice, so far butterknife was awesome and simple, point for it :)
But dagger on the other hand I found it less configurable than roboguice, I have to benchmark if its worth the change but in this case I'm looking on how to inject stuff in lets say Adapters, this is what I made and it works:
public class PeopleAdapter extends BaseAdapter {
private static final String TAG = PeopleAdapter.class.getName();
@Inject
TempoSharedPreferences prefs;
private LinkedList<People> elements;
public PeopleAdapter (LinkedList<People> elements, TempoApplication app) {
this.elements = elements;
app.inject(this);
Log.d(TAG, "registered: " + prefs.isRegistered());
} ....
But on the Activity that creates this instance I have to get an Application that allows to inject, also I have to add to the module every time the classes that use that dependency, roboguice did all that for me and had only one entry point where to modify the stuff.
I'm I doing something wrong? is there any better way to perform this injections? Avoid the declaration of each class on the module?
@Module(injects = {
MainActivity.class,
PeopleAdapter.class
},
library = true)
public class AndroidModule { ....
I'll appreciate any comment or best practice or experience on this.
Thanks!
Dagger automatically generates code that mimics the code you would otherwise have hand-written. Because the code is generated at compile time, it's traceable and more performant than other reflection-based solutions such as Guice. Note: Use Hilt for dependency injection on Android.
You use the @Inject annotation to define a dependency. If you annotate a constructor with @Inject , Dagger 2 can also use an instance of this object to fulfill dependencies. This was done to avoid the definition of lots of @Provides methods for these objects.
You pass the dependencies of a class to its constructor. Field Injection (or Setter Injection). Certain Android framework classes such as activities and fragments are instantiated by the system, so constructor injection is not possible. With field injection, dependencies are instantiated after the class is created.
Dagger cannot support private fields and still support code-generated adapters (to avoid reflection). The way systems like Guice support private fields is they change the access to the field reflectively before accessing them.
You're doing everything right. Dagger needs some more configuration than Roboguice, but is also more powerful (configurable). Did you try scoped graphs or lazy injection already?
Every single class that uses injection must be listed in the injects
param of the module. There's no way to avoid declaration of each class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With