Shane
Shane

Reputation: 471

How do I arrange components with Dagger2 when injecting outside of Activities?

So I've been playing around with Dagger2 with Android for a little bit and I'm starting to wrap my head around how dependencies are injected. I understand that for building components, one of the more common places for this code is in your Application class. This way I can call getApplication().getMyComponent() from my various activities, and inject the relevant fields into the Activity.

However, let's say I have a POJO and I want to inject another POJO into this (say a Service object with a DAO object inside it) and I'm injecting it using POJOComponent. Now, I can't build this in the Application class like before because I'm no longer injecting into an Activity (i.e. no access to 'getApplication()'), so my question is this; should I just build the component in the Service object and then inject the DAO? This doesn't seem correct to me, since if I wanted to inject the DAO into a different object/class, I would need to build my component in that object as well.

Surely I should just have to build my component once and use to inject the DAO into different objects/classes? One way I could think of was using static methods in the Application class but this feels like a hack. Any guidance would be appreciated!

Upvotes: 0

Views: 365

Answers (1)

David Medenjak
David Medenjak

Reputation: 34542

Never use static methods or variable, if you can avoid it. There is most likely a better way.

If you have a android.app.Service, that service itself is/has a Context and you can just as easily get the Application and/or create a new component with that service context.

Then you can just inject it as you would with activities, or fragments.


If you are talking about Service as some sort of business logic class, then you have access to the constructor. In this case you can—and should—make use of Constructor injection.

If you need MyDao, put it in the constructor. Don't get into the habit, that each class grabs and takes the dependencies it needs. If something wants to use your service, it needs to supply it with the dao.

Wherever you use your Service class, there you should think about how to provide those dependencies. This will most likely be in an Activity, Application, Fragment, or Service again, where—as already pointed out above—you'll have access to the application and component again.

Upvotes: 1

Related Questions