What is the good example of using DI (Dagger) in t

2019-08-09 06:32发布

问题:

I'm trying to create modular architecture for my Android app and now I'm looking into Dagger DI library. It's really awesome tool, but I don't want to misuse it and currently I have numerous questions like:

  • Should I wrap everything (like Activities or Fragments, or event separate Views) into modules or only common used parts of app (likes services for querying data with login, data layer)?
  • Better use with Android annotations. Android Annotations is another cool library I faced but it seems to play well with UI layer making easy ealing with Views, Fragments and removing some boilerplate code. But how doest it play with Dagger?

If you have a good example of open source project using DI please refer to me. I really want to follow best practices.

回答1:

Take a look at:

  • Jake Wharton's u2020 app;
  • u2020-mortar - port of Jake Wharton's u2020 app with use of Mortar & Flow;
  • u2020-mvp - another port by Live Typing with MVP pattern in mind.


回答2:

Dependency injection is usually used to add a layer of separation and makes things even less coupled. For Android the library I recommend is Dagger2.

I would really suggest you to check this boilerplate since it is fully based on DI using Dagger2.

The dependencies currently handled by the boiler plate are the following:

  • Database dependency: encapsulates all the database operations.
  • Shared preferences dependency: deals with shared preferences.
  • Local files dependency: which deals with saving on files.
  • Analytics dependency: covers all the operation of reporting events to your analytics backend (GA, Segment, FB, Flurry ..)
  • Logging dependency: encapsulates all the operations related to logging to your console
  • Api dependency: encapsulates all the API related operations

The power of dependency injection comes really handy especially for testing since you can easily switch your dependencies in the test environment to dummy dependencies.