Itai Hanski
Itai Hanski

Reputation: 8700

Activity Field Injection Using Dagger 2

When using Constructor Injection with Dagger2, I can really see how the concept of dependency injection is implemented:

 public class Dependent {

     @Inject
     public Dependent(Dependency dependency) {
         // We're dependent on an instance of the Dependency class
         // but we don't care who provides it
     }

 }

But when it comes to an Activity, because Android is instantiating it for us, we need to use Field Injection to satisfy our dependencies. All of the examples I found online suggest something like this:

  1. Create a @Module class to provide our dependency.
  2. Create a @Component interface and call the generate builder to instantiate it. Most of the examples perform this in the Application class and save a reference as a member.
  3. In our Activity - create our @Inject field, and in the onCreate(..) method, get a reference to the Component from our Application and initiate the injection.

My problem with this approach is that it doesn't feel loosely coupled, which is what we're trying to achieve.

 public class DependentActivity extends Activity {

     @Inject Dependency mDependency;

     public void onCreate(final Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         ((MyApplication) getApplication()).getComponent().inject(this);

         // We're dependent on an instance of dependency
         // but now we not only know who provides it,
         // we explicitly initiate the injection
     }

 }

What am I missing?

Upvotes: 4

Views: 1545

Answers (1)

Chris Thoma
Chris Thoma

Reputation: 499

You initiate the injection, yes, but you don't have to have any knowledge about where it's coming from (meaning how the object is created, or how you get it). You could switch out your component classes that your Application gives you and your activity wouldn't change. You could switch out the module that provides your Dependent object and nothing in your activity would change. What this injection gives you is the ability to have your activity only deal with USING the injected object. Usually without dependency injection your activity would have to understand how to instantiate it, how to initialize it with whatever it needs, and also how to use it. This allows you to easily swap in and out components, change the way it's initialized, or whatever and your activity (ideally) wouldn't have to change a single thing.

Upvotes: 4

Related Questions