-
Notifications
You must be signed in to change notification settings - Fork 8
Find component
Let's imagine two situations:
- Your class doesn't have its own component and needs the
AppComponent
to inject dependencies; - The builder needs some Dagger component dependencies to build the component.
We will start from the first situation.
For example, you have bound the AppComponent
in the Application class.
class App : Application(), IHasComponent {
override fun onCreate() {
super.onCreate()
XInjectionManager.instance
.bindComponent<AppComponent>(this)
.inject(this)
}
override fun createComponent(): AppComponent =
DaggerAppComponent.builder().build()
}
And in the MainActivity
you need this component, so you call the findComponent<AppComponent>()
method.
class MainActivity : AppCompatActivity() {
//...code...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
XInjectionManager.instance.findComponent<AppComponent>().inject(this)
}
}
Make sure, the the needed component is still alive, otherwise you will get a ComponentNotFoundException
exception.
So now we are going to use the findComponent<AppDependencies>()
method to look for the dagger component dependency.
Imagine you have an AppComponent
, that implements the AppDependencies
interface.
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent : AppDependencies {
fun inject(app: App)
}
@Module
class AppModule {
@Singleton
@Provides
fun provideTextHolder() = TextHolder()
}
interface AppDependencies {
fun provideSingletonTextHolder(): TextHolder
}
You have bound the AppComponent
to the Application.
class App : Application(), IHasComponent {
override fun onCreate() {
super.onCreate()
XInjectionManager.instance
.bindComponent<AppComponent>(this)
.inject(this)
}
override fun createComponent(): AppComponent =
DaggerAppComponent.builder().build()
}
In the feature module, you have a FeatureAComponent
that requires the AppDependencies
.
@FeatureAScope
@Component(dependencies = [AppDependencies::class])
interface FeatureAComponent {
fun inject(fragment: FragmentA)
}
Ho do we get the AppDependencies
? The answer is just call the findComponent<AppDependencies>()
method. InjectionManager
knows about AppComponent
and knows that this component implements AppDependencies
interface, so it can return it to you.
class FragmentA : Fragment(), IHasComponent {
@Inject
lateinit var textHolder: TextHolder
//...code...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
XInjectionManager.instance
.bindComponent<FeatureAComponent>(this)
.inject(this)
}
override fun createComponent(): FeatureAComponent =
DaggerFeatureAComponent.builder()
.appDependencies(
XInjectionManager.instance.findComponent<AppDependencies>()
)
.build()
}
That's it. But you need to be sure that the AppComponent
is still alive.