Sobes.tech
Junior — Middle

Tell about your experience with Dependency Injection in projects.

sobes.tech AI

Answer from AI

In Android projects, I used Dependency Injection (DI) to simplify dependency management and improve code testability. Most often, I used the Dagger/Hilt library.

DI allows:

  • To invert control over object creation,
  • To easily replace implementations for testing,
  • To reduce component coupling.

Example with Hilt:

@HiltAndroidApp
class MyApp : Application()

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides
    fun provideApiService(): ApiService {
        return Retrofit.Builder()
            .baseUrl("https://api.example.com")
            .build()
            .create(ApiService::class.java)
    }
}

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject lateinit var apiService: ApiService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // apiService is ready to use
    }
}

This approach significantly simplifies scaling and maintaining the application.