简体   繁体   中英

Dagger 2: Providing dependencies in Application Module vs injecting them

I was trying to add Dagger 2 to my android app. As far as I understand, Dagger will construct my object(which I am trying to inject) as long as its' dependencies are provided(in a Module) or they are injected using some form of injection(constructor/method).

I would like to know if there's a distinction between when a dependency should be provided in a Module(say Application Module) vs when its' injected using a constructor injection, and if there is any rule of when I should do which?

Both are the same. Constructor injection basically eliminates the need to write a provider method. As a rule of thumb, I mostly use it for classes with a no-args constructor for easy injection, like Util classes.

There's no difference really. As long as Dagger knows how to construct an instance, that's all that matters.

The reason there are two ways to do it is that you don't always have the ability to use constructor injection, for instance if the class is part of a library that you are using but which you don't have the source (and so you can't add @Inject on one of the constructors).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM