While reading the docs for dagger 2 I cannot find an easy way to provide a dependency when building an app for testing. The only clue I've found is this:
Dagger 2 doesn't support overrides. Modules that
override for simple testing fakes can create
a subclass of the module to emulate that behaviour.
Modules that use overrides and rely on dependency injection
should be decomposed so that the overridden modules are instead
represented as a choice between two modules.
I don't understand how I would set up such a configuration on Android, anyone can explain?
This is currently impossible with Dagger 2 (as of v2.0.0) without some workarounds. You can read about it here.
I've proposed one workaround but this requires changes to the production code.
In short:
provide additional setter for #Component (e.g. in Android setter in Application class)
test component must extend the production component
For more information please check both links. Hope this issue will be addressed in future versions of Dagger 2.
Related
Square Inc. has presented it's internal modular architecture at Droidcon SF'19:
https://www.droidcon.com/media-detail?video=380843878
However, I'm a bit confused with some bullets. Could you please help me?
Why do they actually need :wiring modules? I find it adding complexity:
you get extra gradle module for each new feature
you have to make a sort of global injection into your Fragments somewhere in :app, because Fragments defined in :impl modules cannot access it's DaggerComponent, which is defined in :impl-wiring modules. :impl doesn't depend on :impl-wiring, because the dependency is reversed.
you cannot have an Android Dynamic Feature modules, because they should know about it's DaggerComponent in order to inject it's Fragment. But there is no way to do such injection from :app module, which is base-module for Dynamic Features.
so why :wiring modules at all?
One can merge :impl and :impl-wiring, or :fake and :fake-wiring together to eliminate all the issues mentioned above. And also, in :demo-apps one could just have a dependency on either :impl or :fake``, and not on :impl-wiring(or:fake-wiring```).
The creation of this type of modules is to separate even more. With this you generate an abstraction of the type of component you use (koin, dagger) and how. If the project is large, it makes sense to do it.
Currently I generate the following flow of dependencies between modules:
WARNING: Check the directionalities well.
:feature-A:open <- :feature-A:impl -> :feature-A:impl-wiring
:feature-A:impl-wiring -> :feature-A:impl, :feature-A:open
:app -> :feature-A:open, :feature-A:impl-wiring
I'm still not sure if app should depend on open and impl-wiring, or which app should only depend on open and open from impl-wiring.
Eventually, I came up with the following solution:
each feature consists of the following gradle-modules:
api
impl and fake
data:api
data:impl1 ... data:implN and data:fake
data:wiring
ui
demo
So, here api, impl and fake as usual, but I've my data layers separated. I bought myself that I need multiple different implementation of data layers sometimes, for example - if I develop Stock-Charts App, I could rely on Finnhub Open API or MBOUM API or provide fake implementation.
Thus I have data:api, data:implX. Indeed, data:api defines FeatureRepository interface (one or many) and data:implX provides actual implementation for them. In order to bind interface and implementation, I use data:wiring, which defines Dagger modules and component(s). In addition, I keep the same package names within each data:implX module in order to "write-once" the data:wiring module. And to replace one implementation with another, I just change a single line in data:wiring/build.gradle which states a sort of:
implementation project(":data:implA")
to
implementation project(":data:implB")
Also, to break the confusion mentioned in my original question, I introduce ui module, which contains some Views of a particular feature. Fragments go in demo (a standalone app to test feature) or in ui, they refer to viewModel which have some bindings ctor-injected from Dagger component of a feature. But the UI and library are separated here. Fragment instantiates a dedicated Dagger component that uses component dependencies to refer to feature's library bindings, such as interactor or repository etc.
So, to wrap up - separation between UI and business logic implementation (a "library") for each feature makes it possible to solve the issue. Feature's api declares an entry point to it's functionality as a library, and it's global access via Dagger multibindings from :app. So it can be used further in any :demo, :ui and :dynamic-feature.
In Clean Architecture, Robert Martin says:
It is in your Main component that dependencies should be injected by a
Dependency Injection framework. Once they are injected into Main, Main
should distribute those dependencies normally, without using the
framework.
Martin, Robert C.. Clean Architecture (Robert C. Martin Series) (p.
232). Pearson Education. Kindle Edition.
However, Dagger doesn't work this way. Once you set up your dependencies in your application, you still need to depend on it as a framework, e.g. write #Inject annotations to get the dependencies into your classes. There is no way to 'distribute these dependencies' normally, by which I assume he means passing them through a constructor?
Can anyone help clear up my understanding and how best to use Dagger with a Clean style?
On Android, exactly following the advice you quoted from Robert Martin is rather difficult.
This is because there is no precise main entry point. Application, Service and Activity are quasi-entry points as your app will start with the OS instantiating one of these.
However, you don't have control over the constructor or anything really before the lifecycle callbacks. Hence, Dagger 2 on Android has had to rely on manually calling requesting a Component and calling Component#inject() inside lifecycle callbacks quasi-entry points.
However, there have been some measures to address this problem. Dagger-Android goes some way to address this by making you depend on AndroidInjector rather than some series of calls to the Application in order to retrieve the Component manually.
Even further, there is now FragmentFactory that allows control over the constructor of a Fragment, making Fragments amenable for constructor injection. If we use this then we have gone some way to following Robert Martin's advice.
To clarify the original quotation, I believe Robert Martin means that classes apart from the component root should not be polluted with logic for obtaining dependencies (e.g., by reaching into the Application, pulling out the Dagger Component). He is not prohibiting the use of the #Inject annotation which is lightweight meta-data (part of JSR-330) that simply marks a constructor as a site for injection.
In summary, yes - the current way of using Dagger 2 on Android doesn't exactly comply with Robert Martin's excellent recommendation. Nevertheless, this is a known problem and some progress has been made towards solving it.
I got a very useful blog to start my hand with Dagger2. All going I guess going pretty well except an deprecate warning about to Builder.addModule().
I got this link about Unused Modules and Component Dependencies link related but it still not clear to me.
When the Dagger processor generates components, it only requires
instances of modules and component dependencies that are explicitly
needed to supply requests for a binding.
Any one know if any alternative of this deprecated method ?
I have problems migrating my Android app from Dagger to Dagger2.
I use Dagger to inject mocks at different layers during testing (unit , functional device and everything in between).
E.g. I have a NetworkingModule which provides a HttpTransport and a ServerConnector. For some test I just mock the http layer, for others I mock the ServerConnector, and other test use release classes to test integration with a real test server.
These test can be run on all build flavors (debug, release, ...).
I found only descriptions of Dagger2 which set a single static injection configuration per build type - i.e. a release component to bind real classes and a debug component to bind one set of mocks.
I need to find a way to have the test cases replace modules in the application start up phase.
How can I achieve this? In my thoughts I always get stuck when the application triggers the building of the graph for which it has to use a Component which is the implementation of a certain interface which has static annotation of its modules???
To ask differently: Is it possible to compile multiple modules in the same build which provide the same injections? How would I then inject with the right module at run time?
Can someone please draft me a solution for my example of the NetworkingModule.
BTW: I make heavy use of Espresso, Robolectric, and Mockito.
Thx.
Found a solution:
I don't need build specific Components or Modules.
My modules just handle delegates which I implement and set for injecting mocks when testing. This is very cheap for release builds. And for testing I can even effort some reflection for convenience features.
I am evaluating Dependency Injection (DI) frameworks for an Android app. The top contenders are: Dagger (with Butter Knife) and Android Annotations. I understand that Dagger and ButterKnife are from the same source- square and they complement each other. Here're are the key matrices that I am looking for:
Ease of use (our build is based on Gradle and we use Android Studio IDE)
Testing support (we use Robotium for functional testing and RoboLectric for unit testing)
Performance (DI frameworks use reflection, which one is faster?)
AndroidAnnotations
uses compile time annotation processing. It generates a sub class with an underscore apppended to the original name (MyActivity_ generated from MyActivity). So to have it work you always have to use the generated class for references instead of your original class.
It has a very rich feature set, see the list of available annotations.
Butterknife
uses also compile time annotation processing, but it generates finder classes which are used by a central class (ButterKnife). This means that you can use your original class for referencing, but you have to call the injection manually. A copy from the ButterKnife introduction:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
// TODO Use "injected" views...
}
The feature set is not so rich, ButterKnife supports view injection (AndroidAnnotations equivalent would be #ViewByIdand #ViewsById) and some event binding (for a complete list see the namespace directory here, just count the OnXXX event annotations).
Dagger
is a DI implementation for Android, similar to Guice. It also uses compile time annotation processing and generates object graphs which you use for manually injection. You distinguish between application object graph and scoped object graphs for injecting e.g. in activities. Here you see an Application.onCreate example:
#Override public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(getModules().toArray());
objectGraph.inject(this);
// use injected classes
}
I found it is harder to start with dagger, but this might be only my experience. However see some videos here for a better start: 1, 2
From the feature set point of view I would say that Dagger implements functionalities which could be compared to AndroidAnnotation's #EBean and #Bean functionality.
Summary
If you are comparing ease of use, testing support and performance I can't find much difference between using AndroidAnnotation and ButterKnife+Dagger. Differences are in the programming model (use classes with _ instead of using the original ones and call the injection manually) and in the feature set.
AndroidAnnotation gives you a full list of functionalities, but ties you to certain libraries. For example if you use it's rest api you have to use Spring Android. You also have annotations for features like OrmLite (#OrmLiteDao) regardless if you use OrmLite or not.
At the end it is a matter of taste, at least in my opinion.
Here is the Nice article in Dzone blog.
We to need to compare the features of each, such as :
Minimum Jars required
ActionBarSherlock compatibility
Injection for click listeners
POJO injection
Performance
Only Pojo Injection missing in butterknife! So looks like Butterknife is the winner!
Source
Google does ask specifically not to use dependency injection.
But by reading their request they seem to be referring more to the Guice and reflection based DI library's. Libraries such as android annotation use no reflection instead employing compile time generated code, while butterknife and dagger uses a small amount of reflection optimised for android but are supposedly slightly more powerful than android annotation. It really depends on the project and how much of a performance hit you are willing to take. In my opinion just using butterknife is sufficient to speed up code development by itself. If you need slightly more use android annotation and lastly if you are willing to take a slight performance hit due to reflection the best option without absolutely destroying performance with a powerhouse Guice based reflection use dagger + butterknife.
You should give a try at Toothpick.
Toothpick is (per the README):
pure java
fast, it doesn't use reflection but annotation processing
simple, flexible, extensible & powerful, robust & tested
thread safe
documented & Open Source
scope safe : it enforces leak free apps
test oriented : it makes tests easier
it works very well with Android or any other context based framework (such as web containers)
It can even be faster than Dagger 2 in most cases, and it's much simpler.
Note: Yes, I am one of the authors.
Use Android Annotations or Butterknife to ease your coding. But don't go for Roboguice! Roboguice forces your activies, fragments to extend to roboguice classes. Not fun, at all!
Dagger 2 is a much better option. You can use it along with Android Annotations if you'd like. I would just use Android Annotations for a simple app, but these days is good to work more with Dagger.
Seems like Google chooses dagger, as they are developing it jointly with Square, who created it.
Concerning Butterknife and Dagger themselves, there is the SO question difference-between-dagger-and-butterknife-android which clarifies how they complement each other.
The reddit-thread mentioned by #ChrLipp has someone who used all three on the same project, speaks highly of dagger+butterknife but also gives AndroidAnnotations its place:
For dependency injection, butterknife is used for Views, Dagger is
used for all objects and is highly recommended and Android Annotations
creates more of a framework for developing Android instead of
injecting objects into your classes so each library are quite
different from each other. Dagger is equivalent to Guice but is much
much faster. Dagger is more powerful then ButterKnife and Android
Annotations as it injects all objects rather than ButterKnife and
Android Annotations which only inject a certain set of objects.
Dagger can be a pain to setup and configure but is well worth it once
you have it done. But then again, because these are all quite
different from each other, it all depends on what your needs are for
the project.
Also, speaking of each one being quite different, in your project you
can use ButterKnife, Android Annotations and Dagger all in the same
project if you really want to. They each have the same idea but do
something different so you could use them all.
Eventually if you use one of the three, you'll have a hard time transitioning to Android's databinding. That's what's fastest if you need to consider performance:
https://developer.android.com/tools/data-binding/guide.html