In Dagger 2 Dependency Injection...

What is the difference between @Provides, @Binds and @Inject ?

2023-01-31 18:26:47 - Mohamad Abuzaid

-------------------------

[1] @Provides


Annotation for function creating the dependency. Can contain any arbitrary code, where you can define how the dependency should be created.

@Module
class NetworkModule {
  @Provides
  fun provideRetrofit(baseUrl: String): Retrofit {
      return Retrofit.Builder()
          .baseUrl(baseUrl)
          .addConverterFactory(GsonConverterFactory.create())
          .build()
  }
  
  
  @Provides
  fun provideApiService(retrofit: Retrofit): ApiService {
      return retrofit.create(ApiService::class.java)
  }
}


---------------------

[2] @Binds


Just a shortcut used instead of @Provides when you want to bind an interface/abstract class to its implementation.

Note: You can’t use @Provides and @Binds methods together inn the same module class.

@Module
abstract class RepositoryModule {

  @Binds abstract fun bindRepository(repository: RemoteRepository): Repository

  @Binds abstract fun bindDataSource(dataSource: RemoteDataSource): DataSource
}


---------------------

[3] @Inject


Annotates the constructor of a class, if the constructor is public and all its parameters can be provided by Dagger.

class NetworkClient @Inject constructor(
    private val apiService: ApiService,
    private val networkInterceptor: NetworkInterceptor
) {
    
    fun makeRequest(request: Request) {
      // Make the network request using apiService and networkInterceptor objects
    }
}

More Posts