google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.44k stars 2.02k forks source link

Possible to use Dagger2 in my Android library while users of my library might not be using any DI framework? #4034

Open sarimmehdi opened 1 year ago

sarimmehdi commented 1 year ago

If I implement DI using Dagger2 in my Android library but some of the users of my library don't use Dagger2 or they use Hilt (or even Koin) or they don't use any popular DI framework, will my library still work for them? The more I do research on this, the more it seems I have to go the route of manual DI without any 3rd party library.

bcorso commented 1 year ago

It really depends on if you intend to expose DI as part of your public API or only use DI internally in your library.

Typically, we do not recommend exposing DI as part of your public API unless the library is specifically meant for a particular app (i.e. unless you know the app will be using a particular DI framework). If your library needs to support applications with arbitrary (or no) DI framework, then you should not expose DI as part of your public API. Instead, you should have users manually pass in any dependencies your library need from them.

Internally, your library can still use DI. For example, you can use the dependencies the user passes to your library and create an internal Dagger component that your library uses to inject or create objects. Unfortunately, you currently cannot use Hilt internally in your library since Hilt assumes that the application itself uses Hilt, but normal Dagger should work fine.