Hi in our project we use micronaut, and we have a code that looks like this:
beanContext.registerSingleton(foo::class.java, myFooObject)
Now we are trying to work with dagger2, any idea how can I achieve something similar?
CodePudding user response:
In your dagger module you need to declare the provide method with the @Singletone annotation, for example:
@Module
class AppModule {
@Provides
@Singleton
fun provideMyFoo(): MyFoo {
return MyFoo()
}
}
CodePudding user response:
I found a way to do bind a singleton outside of the component. by using @BindsInstance
Here is an example of code where MyFoo is the class I want to inject outside of my comonent :
import dagger.BindsInstance
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [Car::class])
interface ComponentCar {
fun getCar(): Car
@Component.Builder
interface Builder {
@BindsInstance
fun setMyFoo(myFoo: MyFoo): Builder
fun build(): ComponentCar
}
}
Then later in the init code I do something like this:
val component = DaggerComponentCar.builder().setMyFoo(mySingleMyFoo).build()