bitDeveloper
bitDeveloper

Reputation: 132

Multiple Instances of the same type with same implementation in Hilt

I've started using Hilt since it got stable. I'm also new to DI (Dependency Injection).

My question is if I have a single class, say AdapterA, and I want to provide a new instance every time its DI (using @Inject) requests it.

I've used the following code to provide the instance, let me know if I need to add/remove anything to make it work as expected.

// Kotlin

@Module
@InstallIn(ActivityComponent::class)
class AdapterModule {
    
    @Provides
    @ActivityScoped
    fun provideAdapterAInstace(): AdapterA {
        return AdapterA()
    }
}

Now, whenever I'm trying to inject the dependency multiple times in an activity then it always returns the same instance (like a static variable that stores once and reuses numerous times.

// Usage
class ActivityA extends AppCompatActivity {
    
    @Inject
    lateinit var instanceOne: AdapterA
    
    @Inject
    lateinit var instanceTwo: AdapterA

    ...
}

Help me understand what I did wrong or missed here. Thanks in advance.

Upvotes: 2

Views: 2907

Answers (1)

Nitrodon
Nitrodon

Reputation: 3435

Scope annotations tell Dagger to only create one instance in the component with that scope. In this case, that means AdapterA will only be created once per activity. If you want to create a new instance of AdapterA every time, don't provide a scope.

@Module
@InstallIn(ActivityComponent::class)
class AdapterModule {
    
    @Provides
    // unscoped
    fun provideAdapterAInstance(): AdapterA {
        return AdapterA()
    }
}

Upvotes: 5

Related Questions