I'm having trouble injecting a fragment that I contribute via #ContributesAndroidInjector.
I'm trying to build a hierarchy within modules (features). Basically, what I have is:
Core
App
Feature
My AppComponent depends on CoreComponent:
#Singleton
#Component(modules = [CoreModule::class])
interface CoreComponent {
fun getApp(): Application
#Component.Factory
interface Factory {
fun create(#BindsInstance app: Application): CoreComponent
}
}
And initialize as:
#AppScope
#Component(
modules = [
AndroidInjectionModule::class,
ActivityContributor::class,
AppModule::class],
dependencies = [CoreComponent::class]
)
interface AppComponent : AndroidInjector<App> {
#Component.Factory
interface Factory {
fun create(component: CoreComponent): AppComponent
}
}
This part is pretty much straightforward. AppComponent has ActivityContributor which only has one #ContributesAndroidInjector, which is MainActivity.
Now, problem starts when I want to add an encapsulated feature subcomponent. Assume I have two fragments FragmentOne and FragmentTwo in my feature, with some common dependencies as well as their own.
What I want to have is a FeatureSubcomponent which has FeatureModule and FeatureContributor:
#FeatureScope
#Subcomponent(
modules = [FeatureContributor::class,
FeatureModule::class
]
)
abstract class FeatureSubcomponent {
#Subcomponent.Factory
interface Factory {
fun create(): FeatureSubcomponent
}
}
While FeatureModule has dependencies common for both fragments, FeatureContributor is contributing FragmentOne and FragmentTwo with their own modules:
#Module
abstract class FeatureContributor {
#ContributesAndroidInjector(modules = [FeatureOneModule::class])
abstract fun featureOneFragment(): FeatureOneFragment
#ContributesAndroidInjector(modules = [FeatureTwoModule::class])
abstract fun featureTwoFragment(): FeatureTwoFragment
}
And of course, I add FeatureSubcomponent as a subcomponent to AppModule:
#Module(subcomponents = [FeatureSubcomponent::class])
And if you scroll up, you'll see AppModule is included in modules of AppComponent.
Problem is, while it's compiling and running, it crashes once it reaches to any feature fragments due to No injector factory bound for error.
Roughly summarising my structure:
CoreComponent
AppComponent
FeatureComponent (SUB)
FeatureOneComponent (SUB)
FeatureTwoComponent (SUB)
Anyone has ideas about why or how it should be instead or am I missing something ?
Edit
Here's the diagram I prepared to make it easier to understand hierarchy
Dagger android does injection by finding the closest injector in the current scope. For Fragment, it is the containing Activity and for Activity it is the Application instance.
When you call AndriodInject.inject(this) in the Fragment it is goes up the hierarchy to find injector and then injects the Fragment.
Have you extended DaggerAppCompatActivity/implemented the HasFragmentInjector?
Another thing I see is, why create subcomponent again when #ContributesAndroidInjector already creates a sub component internally for you?
#ContributesAndroidInjector.modules is a way for talking to the generated subcomponent. So the relationship between Activity and FeatureFragment must be established in the subcomponent that the #ContributesAndroidInjector will be generating.
Right now your hierarchy is like this since you have deliberately specified FeatureSubComponent to be subcomponent of the AppComponent
App -> FeatureSubComponent -> [A, B] (generated)
\
\---> MainActivitySubcomponent (generated by contributesAndroidInjector).
What you actually need is:
App -> MainActivitySubComponent (generated) -> [Feature A , Feature B] (generated)
To do this
#ContributesAndroidInjector(modules = [FeatureContributor::class])
abstact fun mainActivity() : MainActivity
Feature contributor can have #ContributesAndroidInjectors inside. When Dagger compiler sees that FeatureContributor has #ContributesAndroidInjectors, it makes the subcomponent generated by those to be the subcomponent of the activity since it is the parent.
Which basically means Activity -> Fragment hierarchy.
Related
I need a solution where i could inject Fragment arguments/extras (one Longand one String to be specific) into Fragment's viewmodel and based on these values viewmodel could run it's setup in init {..}
All the ViewModel's injections are fine, dependencies in ViewModel's #Inject construct([dependencies]){..} are provided and working correctly.
My SubComponent looks like this at the moment :
`
#Scope
annotation class MyFragmentScope
#MyFragmentScope
#Subcomponent(modules = [MyFragmentModule::class])
interface MyFragmentSubcomponent : Injector<MyFragment> {
#Subcomponent.Builder
interface Builder : Injector.Factory<MyFragment>
}
#Module
abstract class MyFragmentModule {
#Binds
#IntoMap
#MyFragmentScope
#ViewModelKey(MyFragmentViewModel::class)
abstract fun bindMyFragmentViewModel(
viewModel: MyFragmentViewModel
): ViewModel
}
`
I would be super thankful for any support
Cheers
I tried to create a new ViewModelFactory with additional parameter, but sadly that didn't work out
Tried to use Hilt or Assisted Injection, which also didn't work out since my project is strictly restricted to Dagger v 2.16, if i try to update - tons of bugs arise from this old codebase, it would take months rewriting everything.
Maybe i just did something wrong
With Dagger2 it's easy to explicitly create components and list their dependencies. But I can't seem to find a way to provide different implementations of an interface to lets say a fragment.
For example, my app has 2 production modes: paid and free.
I have a PaidActivity and a FreeActivity, both of which start exactly the same Dashboard fragment with an Analytics class. For Paid I provide a PaidAnalytics implementation, for Free I provide a FreeAnalytics implementation.
With Dagger2 it's easily achieved by just listing a Paid or a Free Module in the Activity's Component (or Subcomponent).
#Module
abstract class FreeActivityModule {
#ContributesAndroidInjector(
modules = [
FreeAnalyticsModule::class,
DashboardFragmentModule::class
]
)
abstract fun injectFreeActivity(): FreeActivity
}
#Module
abstract class PaidActivityModule {
#ContributesAndroidInjector(
modules = [
PaidAnalyticsModule::class,
DashboardFragmentModule::class
]
)
abstract fun injectPaidActivity(): PaidActivity
}
#Module
abstract class DashboardFragmentModule {
#ContributesAndroidInjector
abstract fun injectDashboardFragment(): DashboardFragment
}
class DashboardFragment : Fragment() {
...
#Inject
lateinit var analytics: Analytics
...
}
With Dagger Hilt I couldn't find a way to do this.
With Dagger it is impossible to replace dependencies at runtime in my use case.
During one of the Google Hilt sessions they recommended to use an if else statement in a Provides method: https://youtu.be/i27aNF-kYR4?t=3355 (that's what I prefer to avoid).
The answer above doesn't understand my question, because they are qualifying dependencies at compile time which I can't do. Since my fragment never knows the place it's used and I don't want to just duplicate code.
Here's an example where you can see exactly what I'm doing and that it can't be achieved with Hilt by design: https://github.com/dmytroKarataiev/daggerAndroidvsHiltRuntimeDependencies
I think we could leverage Hilt's Qualifier feature to solve this multi binding issue.
Here is some resources I found: https://developer.android.com/codelabs/android-hilt#8
I quote:
To tell Hilt how to provide different implementations (multiple bindings) of the same type, you can use qualifiers.
I think it's a way for Hilt to differentiate different implementations of the same interface.
To setup your Hilt module:
#Qualifier
annotation class PaidModule
#Qualifier
annotation class FreeModule
#InstallIn(ActivityComponent::class)
#Module
abstract class PaidActivityModule {
#ActivityScoped
#Binds
#PaidModule
abstract fun bindPaidModule(impl: PaidActivity): YourInterface
}
#InstallIn(ActivityComponent::class)
#Module
abstract class FreeActivityModule {
#ActivityScoped
#Binds
#FreeModule
abstract fun bindFreeModule(impl: FreeActivity): YourInterface
}
To inject:
#FreeModule
#Inject
lateinit var freeActivity: YourInterface
#PaidModule
#Inject
lateinit var paidActivity: YourInterface
In my Android project, I have two project modules, an main module and a core module.
In main module, I have a dagger component, MainComponent:
// it has dependency on CoreComponent
#Component(modules = [MyModule::class], dependencies = [CoreComponent::class])
#FeatureScope
interface MainComponent {
fun inject(mainActivity: MainActivity)
}
As you can see above, MainComponent has a dependency on CoreComponent. It also has a custom scope annotation #FeatureScope.
In core module I have another dagger component called CoreComponent:
#Component(modules = [CoreModule::class])
#Singleton
interface CoreComponent {
fun getExpensiveObject(): ExpensiveObject
}
#Module
class CoreModule {
#Provides
#Singleton
fun provideExpObj(): ExpensiveObject = ExpensiveObject()
}
The CoreComponent is annotated by Dagger defined #Singleton scope.
I build the Main component in onCreate() of Application class:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
//build main component along with core component
mainComponent = DaggerMainComponent
.builder()
.myModule(MyModule())
.coreComponent(DaggerCoreComponent.builder().build())
.build()
}
}
CoreComponent & its providers are annotated by #Singleton, while MainComponent & its providers are annotated by custom annotation #FeatureScope.
Question one: From lifetime perspective, does the code mean the lifetime of objects in MainComponent is shorter than that in CoreComponent due to the scope annotations (#Singleton in CoreComponent and #FeatureScope in MainComponent)?
Question two: Since the components are built in Application class onCreate() which is the entry point of app at runtime, am I right that even though components in two project modules are annotated by different scope annotation, their objects basically have the same lifetime as the whole app's at runtime?
(I ask those questions because my understanding is that the Dagger defined #Singleton scope has the longest lifetime, but I get confused by that with my project)
Yes, the fact that CoreComponent is annotated with #Singleton and the component instance is created in the Application means that there will be a single ExpensiveObject created in the lifetime of the application.
Concerning the custom annotation (#FeatureScope)
The component implementation ensures that there is only one provision of each scoped binding per instance of the component.
ref
But since, the MainComponent is created only once per application, this custom annotation is effectively the same as the Singleton annotation.
If you want a feature-scoped object then you should remove it from the MainComponent and have this annotation only on a sub-component. Read the dagger tutorial, and in particular the step 13.
Annotating both WithdrawalLimiter and UserCommandsRouter with
#PerSession indicates to Dagger that a single WithdrawalLimiter should
be created for every instance of UserCommandsRouter.
#PerSession
final class WithdrawalLimiter { ... }
#PerSession
#Subcomponent(...)
interface UserCommandsRouter { ... }
I am using Dagger2 and I want to know if it is possible to use the new Android Injector for dependent components? I have seen a few tutorials that use subcomponents and the base App component will just inject everything.
AppComponent
#Singleton
#Component(modules = [AndroidSupportInjectionModule::class])
interface ApplicationComponent {
fun inject(app: App)
#Component.Builder
interface Builder {
fun build(): ApplicationComponent
#BindsInstance
fun app(app: Context): Builder
}
}
QueueComponent
#QueueScope
#Component(dependencies = arrayOf(ApplicationComponent::class), modules = [ScreenBindingModule::class])
interface QueueComponent {
}
ScreenBindingModule
#Module
abstract class ScreenBindingModule {
#ContributesAndroidInjector()
abstract fun queueActivity(): QueueActivity
}
In the onCreate I have added AndroidInjection.inject(this) but the problem is that the app crashes with the exception:
Caused by: java.lang.IllegalArgumentException: No injector factory bound for Class....
No, this will not work without more configuration. As in AndroidInjection.inject:
Application application = activity.getApplication();
if (!(application instanceof HasActivityInjector)) { /* ... */ }
Given an Activity there's no easy way to determine which wider-than-Activity-scoped object should be used to create the Activity's subcomponent, so dagger.android tries to cast the Application to the type HasActivityInjector. Your Application evidently exposes HasActivityInjector to get that error message—likely by marking DaggerApplication or your custom subclass of DaggerApplication in your manifest—but that implementation just returns the DispatchingAndroidInjector<Activity> that searches a multibindings map.
Though #ContributesAndroidInjector automatically installs into that map, each of your Components (ApplicationComponent and QueueComponent) contains a different map, and your DaggerApplication only consults the one in ApplicationComponent.
In order to make this work with component dependencies, you would need to have your Application subclass's activityInjector method return a different AndroidInjector implementation, which creates/fetches a QueueComponent instance and reads the multibound Maps (which would necessarily be exposed on QueueComponent). Unfortunately, there isn't really a way to bind multiple elements into your ApplicationComponent's existing multibound map, as tracked in https://github.com/google/dagger/issues/687, so making this work would involve a custom AndroidInjector implementation at least.
#ContributesAndroidInjector()
abstract fun queueActivity(): QueueActivity
Which module contains this part of code? In QueueComponent You are added ScreenBindingModule::class, but define injector factory in another class - QueeScrennBindingModule::classs.
It's just a typo or it's really two different classes?
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()