Migrating to Hilt from Dagger2 - android

I am trying to follow the Hilt migration guide here:
https://dagger.dev/hilt/migration-guide.html
And have annotated all my modules with:
#InstallIn(SingletonComponent::class)
However I am running into issues with my "Contributor" Modules for services, fragments and activities.
I have one module for each,
#Module
#InstallIn(SingletonComponent::class)
abstract class FragmentContributorModule {
#ContributesAndroidInjector
internal abstract fun contributeMyFragment(): MyFragment
}
#Module
#InstallIn(SingletonComponent::class)
abstract class ActivityContributorModule {
#ContributesAndroidInjector
internal abstract fun contributeMyActivity(): MyActivity
}
#Module
#InstallIn(SingletonComponent::class)
abstract class ServiceContributorModule {
#ContributesAndroidInjector
internal abstract fun contributeMyService(): MyService
}
During compile I am getting errors for each one of the "contribute" functions:
com.test.ActivityContributorModule_ContributeMyActivity$defaultsDebug is missing an #InstallIn annotation. If this was intentional, see https://dagger.dev/hilt/compiler-options#disable-install-in-check for how to disable this check.
I have also tried to use ServiceComponent::class, FragmentComponent::class and ActivityComponent::class for each Module with no luck. I am trying to migrate the project in pieces so I don't think I can remove these until everything is upgraded to Hilt.
Any ideas?

The answer is here:
Warning: Modules that are not annotated with #InstallIn are not used
by Hilt. Hilt by default raises an error when unannotated modules are
found, but this error can be disabled.
Was not 100% clear to me at first, but the contributor modules I have for services/fragments/activities are only used with Dagger, not Hilt. So if you are trying to migrate you project in pieces you can leave those module as is until you start to provide Hilt entry points for your services/fragments/activities. However if you do that, you will need to tell Hilt to ignore the error it throws for missing #InstallIn.
More info on how to disable that here:
https://dagger.dev/hilt/compiler-options.html#disable-install-in-check
By default, Hilt checks #Module classes for the #InstallIn annotation
and raises an error if it is missing. This is because if someone
accidentally forgets to put #InstallIn on a module, it could be very
hard to debug that Hilt isn’t picking it up.
This check can sometimes be overly broad though, especially if in the
middle of a migration. To turn off this check, this flag can be used:
-Adagger.hilt.disableModulesHaveInstallInCheck=true.
Alternatively, the check can be disabled at the individual module
level by annotating the module with #DisableInstallInCheck.

Related

Why a class can't find #Named provider from a Hilt module?

I am migrating the application from Dagger2 to Hilt, and I started it from creating a single activity that uses Hilt
I wrote the inject annotation for one of the dependencies inside the activity
I have the provider method(it has a return type) in my HiltApplicationModule
configService is one of the dependencies provideRemoteConfig needs, so for that I also have a provider named method
Moreover, one of the dependencies that RemoteConfig also uses - it uses that same configService that we need to inject
When I run the build, I receive the error
#javax.inject.Named("config_service_merchant") com.example.configapp.ConfigService cannot be provided without an #Provides-annotated method and
public interface ApplicationComponent extends AndroidInjector {
^
#javax.inject.Named("config_service_merchant") com.example.configapp.ConfigService is injected at
At this point, I am confused why it can't find it if I have the method
My assumption that it tries to find it in Dagger2 modules and application components that I still have in the project, but I am not sure.
Why does configService's provider cannot be found to be injected in one of the classes(particularly AnalyticsConfig)?

Inject WorkManager with Hilt but getting error "Dagger does not support providing #AssistedInject types."

While injecting WorkManager using HILT, compiler throwing below error
"Dagger does not support providing #AssistedInject types"
Have followed all mentioned steps from below link
https://developer.android.com/training/dependency-injection/hilt-jetpack
PFB Coding snippet and build.gradle dependencies for HILT and Worker
WorkerClass
Dependencies
To Resolve the issue have seen and implemented various S.O. post but no luck.
Whereas, if I didn't use both #HiltWorker and #AssistedInject and
removed other dependencies from object constructor code compiles and
run successfully but field injection for required dependencies won't
work.
Therefore not sure whether its library issue or some implementation issue.
And thank you for your support and answer in advance!
Edit :
(Adding WorkerModule.kt code)
#Module
#InstallIn(SingletonComponent::class)
object WorkerModule {
#Singleton
#Provides
fun provideWorkerModule(context: Context,
workerParameters: WorkerParameters
// appNetworkService: AppNetworkService,
// appDatabaseService: AppDatabaseService
): PaymentTrackerWorker {
// return PaymentTrackerWorker(context, workerParameters,appNetworkService,appDatabaseService)
return PaymentTrackerWorker(context, workerParameters)
}
}
The error states that you are trying to #Provides a class with an #AssistedInject constructor. This makes sense: after all, there is no way to get the right instance of WorkerParameters in a singleton context.
Fortunately, WorkerModule is also completely unnecessary, as HiltWorkerFactory already knows how to create any #HiltWorker-annotated class. Simply remove the module, and follow the tutorial to ensure that HiltWorkerFactory is installed in WorkManager.

How to easily replace production Hilt modules with fakes in all tests

My Android production is code full of Hilt modules that install various production implementations:
#Module
#InstallIn(ApplicationComponent.class)
public abstract class TimeModule {...}
#Module
#InstallIn(ApplicationComponent.class)
public abstract class DatabaseModule {...}
In all my instrumented tests, I would like to replace those bindings with fakes. My test codebase includes modules that bind fake implementations, but having two modules provide the same class obviously causes compile-time errors.
The Hilt documentation recommends using #UninstallModule(), but that means I'd have to add UninstallModule for every single production module in every single test. That seems like the wrong approach.
How would one normally replace production modules with fake modules? And is there a way to install modules from another module like Guice does, so I could remove #InstallIn from all my production modules and instead simply have one ProductionModule that installs all the individual modules? That would make it easier to just uninstall one module in tests.
How would one normally replace production modules with fake modules?
Probably how it's normally done, is like the documentation said with the UninstallModule annotation. But here is an alternative, which I like to use, using build flavors:
I like to organize my project, so there are mock and live flavors. And there are 3 folders inside my app module: src/main/kotlin with Activities, Fragments etc..., src/mock/kotlin where my fake bindings live, and finally src/live/kotlin where my real production bindings live.
Here's the relevant config from my app level build.gradle.kts:
android {
productFlavors {
flavorDimensions("environment")
register("mock") {
dimension = "environment"
}
register("dev") {
dimension = "environment"
}
register("prod") {
dimension = "environment"
}
sourceSets {
getByName("mock").java.srcDir("src/mock/kotlin")
getByName("dev").java.srcDir("src/live/kotlin")
getByName("prod").java.srcDir("src/live/kotlin")
}
}
}
Project structure overview
Inside the live InteractorModule:
#Module
#InstallIn(ApplicationComponent::class)
abstract class InteractorModule {
#Binds
abstract fun bindTodoInteractor(interactor: TodoInteractorImpl): TodoInteractor
}
Inside the FakeInteractorsModule:
#Module
#InstallIn(ApplicationComponent::class)
abstract class InteractorModule {
#Binds
abstract fun bindTodoInteractor(interactor: TodoInteractorFake): TodoInteractor
}
So now you can use the build variant tab to change between the real and the mock implementations of your interfaces. So if you want to use your fakes inside your instrumentation tests use the mock flavor while running the tests.
One upside of this method, is that by changing the build variant, you can swich between your instrumentation tests using your fakes to using the live implementations. Conversly, you can use your fake implementations inside the actuall application, which can be nice, if you just want to try out the app with mock data.
I hope this helped a bit to at least promote some ideas, on how you can solve this "two implementations for one interface" dilemma!

Removing #JvmSuppressWildcards not working android dagger 2.25.2

I have updated my dagger with 2.25.2 and as per the latest release we don't need #JvmSuppressWildcards this annotation anymore. I remove it and trying to run the app but its not working showing dagger build error like:
error: [Dagger/MissingBinding] java.util.Set<? extends com.test.deeplinking.handlers.DeeplinkHandler> cannot be provided without an #Provides-annotated method.
My dagger module:
#Module
abstract class DeeplinkHandlerSetModule {
#Multibinds
abstract fun deeplinkHandlers(): Set<DeeplinkHandler>
#Provides
#JvmStatic
fun provideEntryDeeplinkHandler(
set: Set<DeeplinkHandler>, .., ..
) = EntryDeeplinkHandler(set, ..., ...)
}
Adding #JvmSuppressWildcards like set: Set<#JvmSuppressWildcards DeeplinkHandler> working fine. Even does it support from dagger 2.25.2 version? Anyone can confirm it?
Why do you think #JvmSuppressWildcards is not needed anymore?
In the release notes there isn't anything related with it, as far as I can tell.
https://github.com/google/dagger/releases
The only similar item is not needing #JvmStatic on module objects.

Dagger 2 using classes generated by another library

I have a homemade library that generates DataMapper classes.
They are generated with #Singleton and #Inject annotations to be able to inject them where i need them.
But where it doesn't work is when Dagger tries to create the dependency tree, this error shows :
:data:kaptGenerateStubsDebugKotlin
e: /Users/me/myproject/data/build/tmp/kapt3/stubs/debug/com/myproject/data/di/DataComponent.java:11: error: [Dagger/MissingBinding] error.NonExistentClass cannot be provided without an #Inject constructor or an #Provides-annotated method.
public abstract com.myproject.domain.repository.ContentRepository contentRepository();
^
error.NonExistentClass is injected at
com.myproject.data.repository.ContentDataRepository.<init>(…, myGeneratedDataMapper, …)
com.myproject.data.repository.ContentDataRepository is injected at
com.myproject.data.di.module.DataModule.contentRepository(contentDataRepository)
com.myproject.domain.repository.ContentRepository is provided at
com.myproject.data.di.DataComponent.contentRepository()
:data:kaptDebugKotlin
:data:kaptDebugKotlin FAILED
Involved classes are :
DataModule (module for dagger)
#Module
class DataModule {
#Provides
#Singleton
fun contentRepository(contentDataRepository: ContentDataRepository): ContentRepository = contentDataRepository
}
DataComponent (component for dagger):
#Singleton
#Component(modules = [DataModule::class])
interface DataComponent {
fun contentRepository(): ContentRepository
}
ContentDataRepository
#Singleton
class ContentDataRepository #Inject constructor(
private val myGeneratedDataMapper: MyGeneratedDataMapper
) : ContentRepository {
...
}
MyGeneratedDataMapper
#Singleton
class MyGeneratedDataMapper #Inject constructor() {
...
}
The thing is, if i disable kapt of dagger dependency in gradle.build, then build, then enable it, then build, it works.
If i do a clean + build, it doesn't work, same error.
I want to make it work in one row.
I don't know if you are using AS3.2 or AS3.3 with androidX artifacts or not but Maybe this is the case with you too.
so when i migrated to androidX artifacts in AS3.2 i got hit with bunch of NonExistentClass errors ends the build with
kaptGenerateStubsDebugKotlin
:data:kaptDebugKotlin
:data:kaptDebugKotlin
I finally found out that it has something to do with Dagger itself and degraded the version from 2.17 to 2.16 now the latest version of Dagger2 is 2.18 which i can't use due to this bug / feature [they forgot about].
Update:
i found the solution and it just came today so here is the issue tracker link:
https://issuetracker.google.com/issues/115738511
so the bug was not in the Dagger but it was with Jetifier and i totally ignored the fact that it was set enabled during migration
here's the solution i copied from the link:
Sorry jetifier beta01 was not binary compatible with alpha10.
We have published beta02 that should fix this issue.
Please try:
buildscript { dependencies {
classpath 'com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta02' } }
You're probably not going to like my answer but the order is kinda random.
Look at this thread for some more explaining and maybe some more guidance but, if you want to verify you are running first look at Gradle plugins and how to use them

Categories

Resources