Android dagger how to hide generated factory classes from consuming module - android

Is there a way to hide dagger generated factory classes from consuming app?
I have a library module with its own component and consuming app obvisouly can see all the dagger generated class(e.g. LibraryData_factory.java) from the library module. But I just want to provide some public class to the consuming app and hide the rest of them, for example:
internal interface Person
internal class Adult #Inject constructor(): Person
internal class Car(val driver: Person): Vehicle
#Module
object LibraryModule {
#Provides fun provideCar(person: Person): Vehicle {
return Car(person)
}
}
How can I hide the generated Adult_factory class from consuming app?

Related

Android + Hilt: Dependency cycle injecting a repo into a service which is going to be used by an activity

I have a Service (which is going to be used in an activity) that needs a Repository to be injected in it. I tried providing it with constructor injection (the preferred way), but I was not able to do it like this because I also need a module with a #Provides for the Service itself, who is going to be used in an activity through field injection (because as far as I know I cannot use constructor injection in Activities), and if I do constructor injection for the repo then, when I need to create the #Provides for the service:
#Provides
#Singleton
fun provideMyService(): MyService {
return MyService()
}
It complains about missing constructor parameters for MyService and, if I do:
#Provides
#Singleton
fun provideMyService(myService: MyService): MyService {
return myService
}
It complains about a "Dependency cycle".
In resume, my activity uses a service (located in one module of my app) and the service needs the repo (located in another module), and I need to find the correct dependency injection way for the whole "chain" to work.
For now, activity gets Service injected -through field injection- > Service gets Repository injected -through an EntryPoint-
One of the. things I tried is a module with the next piece of code:
#Provides
#Singleton
fun provideTrackRepository(trackRepository: TrackRepository): TrackRepository {
return trackRepository
}
#EntryPoint
#InstallIn(SingletonComponent::class)
interface TrackRepositoryInterface {
fun getTrackRepository(): TrackRepository
}
And when building I get the following message:
/myApp/app/build/generated/hilt/component_sources/debug/com/myApp/myApp/app/AWApplication_HiltComponents.java:141:
error: [Dagger/DependencyCycle] Found a dependency cycle: public
abstract static class SingletonC implements
com.myApp.repository.local.Dependencies.TrackRepositoryInterface,
^
com.myApp.repository.local.TrackRepository is injected at
com.myApp.repository.local.Dependencies.provideTrackRepository(trackRepository)
com.myApp.repository.local.TrackRepository is injected at
com.myApp.repository.local.Dependencies.provideTrackRepository(trackRepository)
The cycle is requested via:
com.myApp.repository.local.TrackRepository is requested at
com.myApp.repository.local.Dependencies.TrackRepositoryInterface.getTrackRepository()
But if I do:
#Provides
#Singleton
fun provideTrackRepository(): TrackRepository {
return TrackRepository()
}
#EntryPoint
#InstallIn(SingletonComponent::class)
interface TrackRepositoryInterface {
fun getTrackRepository(): TrackRepository
}
It builds and works correctly, but I'm not sure if this second way is a correct way for "dependency injection class providing" or not.
Some people is redirecting me to
https://developer.android.com/training/dependency-injection/hilt-android#android-classes
But I've read this "poor" and "not very clear" -in my opinion- documentation several times, and I'm still stuck.
They're trying to sell Hilt as a very easy dependency injection library, but IMHO working on a multi-module app with Hilt is a true nightmare.

How to Create module class for work manager dependency in kotlin

I have a Worker class that needs an app repository class and the app repository class depends on the API service class. API service class in an interface. I do not know how to create a module class that provides dependency for the Worker class.
I create a module class below
#Module
#InstallIn(ViewModelComponent::class)
object ApiModule {
#Provides
fun provideLaunchListApi(retrofit: Retrofit): API {
return retrofit.create(API::class.java)
}
I doubt that I am not passing correct input for install In that's why It gives missing binding error, can any one suggest me hoe to create a module class for a worker class dependency.

Hilt Testing - Replace internal Hilt-Module in separate Android multi-module app

I have an Android app where the codebase is split into 2 different modules: App and Domain
Goal: I am attempting to use the Hilt provided testing functionality to replace a Domain internal dependency when creating App tests.
In Domain, I have an internal interface with an internal implementation, like below:
internal interface Database {
fun add(value: String)
}
internal class DatabaseImpl #Inject constructor() : Database {
override fun add(value: String) { ... }
}
The above guarantees that the Database can only be used inside Domain and cannot be accessed from elsewhere.
In Domain I have another interface (which is not internal), for use in App, with an internal implementation, like below:
interface LoginService {
fun userLogin(username: String, password: String)
}
internal class LoginServiceImpl #Inject constructor(database: Database) {
override fun userLogin(username: String, password: String) {
// Does something with the Database in here
}
}
In Domain I use Hilt to provide dependencies to App, like below:
#Module(includes = [InternalDomainModule::class]) // <- Important. Allows Hilt access to the dependencies provided by InternalDomainModule.
#InstallIn(SingletonComponent::class)
class DomainModule {
...
}
#Module
#InstallIn(SingletonComponent::class)
internal class InternalDomainModule {
#Provides
#Singleton
fun provideDatabase() : Database = DatabaseImpl()
#Provides
#Singleton
fun provideLoginService(database: Database) : LoginService = LoginServiceImpl(database)
}
This all works perfectly in isolating my implementations and only exposes a single interface outside of Domain.
However, when I need to provide fake implementations inside App using the Hilt guidelines, I am unable to replace the LoginService as I do not have access to InternalDomainModule (because it is internal to Domain only) and replacing DomainModule does not replace LoginService (as it is provided in another Hilt module, namely InternalDomainModule), like below:
#Module
#TestInstallIn(
components = [SingletonComponent::class],
replaces = [DomainModule::class] // [InternalDomainModule::class] is impossible as inaccessible in **App**
)
class FakeModule {
#Provides
#Singleton
fun provideFakeLoginService() : LoginService = FakeLoginServiceImpl() <- Something fake
}
The above leads to only DomainModule being replaced, not InternalDomainModule, which leads to LoginService being provided twice, which makes Hilt unhappy.
Making things not internal to Domain fixes the issue, but defeats the purpose of having a multi-module Android app with clear separations.

Using dependencies from multiple modules dagger 2.11 android

Hi I have two modules seperated in domain packages in my project and have firebase insance service class that injects itself manually using DaggerAppComponent.
Then I have two inject dependencies located on the two modules I mentioned.
ModuleOne has the dependency called storage and ModuleTwo has one called delegator.
When atempting to inject both of these inside my firebase service class, it complains that it can't locate and find the delegator injector from ModuleTwo.
However, if I copy the provides method interface of the delegator into ModuleOne it sort of works(now complains that its bound multiple times but can easily fix that by adding naming convention).
This is a hacky way of doing it which I am not keen to do and just want the ability to use any dependencies from different modules. Is this possible?
Below is my firebase service class
class MyInstanceIdService : FirebaseInstanceIdService() {
#Inject
lateinit var delegator: AccountDelegatorContract
#Inject
lateinit var Storage: StorageContract
override fun onCreate() {
super.onCreate()
AndroidInjection.inject(this)
}
override fun onTokenRefresh() {
DaggerApplicationComponent.builder().application(application as MyApplication).build().inject(this)
val refreshToken = FirebaseInstanceId.getInstance().token
// val pianoStorage: PianoStorage = PianoStorage(this)
sendTokenToServer(refreshToken, storage.getUniqueId())
}
private fun sendTokenToServer(refreshToken: String?, uniqueId: String) {
//TODO: Send this new token to server
delegator.sendPushToken(PushTokenRequest(refreshToken!!, uniqueId))
}
Here is moduleOne which represents the main Module that houses dependencies that are used in multiple domain packages in my application.
#Module
abstract class MainModule {
#ContributesAndroidInjector(modules = [AccountModule::class])
#ViewScope
abstract fun bindInstanceIdService(): MyInstanceIdService
#Provides
#Singleton
#JvmStatic
fun provideApplicationContext(application: Application): Context = application
#Provides
#Singleton
#JvmStatic
fun provideStorageData(storage: MainStorage): StorageContract = storage
}
Here is ModuleTwo that is specific to a domain packages
#Module
abstract class AccountModule {
#Module
companion object {
#ViewScope
#JvmStatic
#Provides
fun providesAccountDelegator(accountDelegate: AccountDelegator): AccountDelegatorContract = accountDelegate
#ViewScope
#JvmStatic
#Provides
fun providesAccountControllerContract(accountNetworkController: AccountNetworkController): AccountControllerContract = accountNetworkController
}
}
My app is organised in different packages that represent a part/domain of the app such as accounts, users, vehicle, message etc etc and with each domain has its own module which defines specific dependencies related to that domain.
My issue is that how can I use dependencies above located on different modules?
Edit: my appCOmponent looks like this
#Singleton
#Component(modules = arrayOf(MainModule::class,
AccountModule ::class))
interface ApplicationComponent : AndroidInjector<DaggerApplication> {
fun inject(MyApplication: MyApplication)
fun inject(myInsanceIdService: MyInstanceIdService)
override fun inject(instance: DaggerApplication)
#Component.Builder
interface Builder {
#BindsInstance
fun application(applicaton: Application): Builder
fun build(): ApplicationComponent
}
}
You add you AccountModule (with provision methods of ViewScope sope) to your AppComponent as well as your subcomponent (declared with #ContributesAndroidInjector bindInstanceIdService), so I wonder how/why this compiles at all. So first of all you should remove the AccountModule from your app component, since it has a different scope anyways and won't do you any good there.
Secondly, you call DaggerApplicationComponent.inject(this) in your MyInstanceIdService, although ApplicationComponent does not include a inject(service : MyInstanceIdService) method. Again, I don't see how/why this would compile. As already mentioned above, you registered a subcomponent (#ContributesAndroidInjector bindInstanceIdService) to inject your service, so you should use it. Your app component does not even have the correct scope to provide all of the objects.
Even worse, you create another AppComponent in your MyInstanceIdService, so even if this would work, you now have 2 singleton components providing 2 different instances of your "singleton" objects. Don't recreate components out of their scope. Use MyApplication.getAppComponent() and use that one!
So after removing the AccountModule from the AppComponent you should make your Application implement the HasServiceInjector, injecting/returning the dispatching injector like you do for your activities. Then inject your service by using AndroidInjection.inject(this).
To sum up:
Check your scopes. A #Singleton component can't provide #ViewScope things.
Don't register modules with different scopes on components, they can't use it anyways
Don't inject an object with a component of a different scope than you need
Don't recreate components when creating subcomponents. Use the existing one!
If you use dagger.android then don't create the components yourself, but implement the correct interface and use AndroidInjection.inject()

How to access app Module Classes from Library Classes in Android?

I created two modules in single android project.
app module(which is default my app module)
and another added library module.
Now app module have many java classes. i want to access .Java class of app module in library module.
Module app has a class DatabaseHelper in package xyz
Now I want to import class DatabaseHelper in Library module.
DatabaseHelper is not recognized by android.
Questions,
Is it possible to import Class from a app module to another module?
any other way.
MyFiles
build.gradle(app)
compile project(':materialList')
setting.gradle
include ':app', ':Library'
Is it possible to import Class from a app module to another module?
This won't be possible as this will be creating a circular dependency.
However there is a pattern that can be utilized in this scenario:
Define the data type : DatabaseHelperContent in the library module
Define an interface DatabaseHelperI in the library module the implementer of which is supposed to provide the data.
Create a DatabaseHelperImpl class implementing the DatabaseHelperI interface, providing the data (this class is in the app module)
Initialize the interface as the instance of class ABC while referring to it in the Application class, so that the data from the class can be dynamically passed to the sub-module.
This would become even simpler with some dependency-injection framework
like Dagger where you can just specify provider of the interface in
the #Module class and use the injected data from the common provider everywhere.
No, there is no way. Rethink your design. Maybe move DatabaseHelper into library project?
In your design, there would be a circular dependency between app module and library module.
The purpose on other modules is to separate completely independent pieces of code and move them to external place. And use them in another modules.
It's quite an old question and I am sure the author has found a solution, but I think the question lacks this answer which many people would like to know.
So, actually, as suggested in other answers, this often might be caused by an issue with your architecture.
But sometimes it may be reasonable. For instance, if you need to access your application id inside a library or in many other cases.
So, if you need to access a resource from the app module in a library module,
it can easily be done with help of dependency injection.
For instance, with Dagger it can be done like this:
1.Create a module that will provide a shared resource.
Let's call it the Integration module.
#Module()
class IntegrationModule {
#Provides
#Named("foo")
fun provideFoo() = "Hey bro"
}
2.Include it in your App component
#Component(modules = [
AndroidSupportInjectionModule::class,
AppModule::class,
IntegrationModule::class,
YourLibraryModule::class
])
#Singleton
interface AppComponent : AndroidInjector<App> {
#Component.Builder
interface Builder {
#BindsInstance
fun app(app: Application): Builder
#BindsInstance
fun context(context: Context): Builder
fun build(): AppComponent
}
}
3.Inject it somewhere in your library
#Inject #Named("foo") lateinit var foo: String
That's it.
Base Dagger implementation code is omitted for simplicity.

Categories

Resources