Skip to Content
Course content

127: Dependency Injection with Dagger/Hilt

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, why do I actually need Hilt? Can't I just pass things in the constructor?

You absolutely can. In a tiny project, manual dependency injection is actually cleaner. But once you hit a certain scale, you run into the "dependency nightmare." Imagine your UserRepository needs a UserApi, which needs an OkHttpClient, which needs a Cache and an Interceptor. To create one repository in your Activity, you'd have to instantiate five other objects in the correct order first.

I've spent far too many hours in legacy codebases manually wiring these graphs. It's tedious and error-prone. Hilt basically acts as the "manager" for your objects. Instead of you saying "Create a Cache, then an OkHttp client, then an Api," you just tell Hilt, "I need a UserRepository," and Hilt looks at the constructor, sees what's missing, and goes and finds (or creates) those dependencies for you automatically.

How do I handle classes I didn't write, like Retrofit or Room?

This is where learners usually get stuck. You can't just put @Inject constructor() on a Retrofit class because you didn't write the Retrofit source code. You can't just go into the library and add annotations. For these "third-party" dependencies, we use Hilt Modules.

Think of a Module as a guidebook. You're telling Hilt: "Whenever someone asks for a NewsApi, run this specific function to create it." Here is how I usually set up a network module:

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    @Singleton
    fun provideRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://api.news.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Provides
    @Singleton
    fun provideNewsApi(retrofit: Retrofit): NewsApi {
        return retrofit.create(NewsApi::class.java)
    }
}

Notice that provideNewsApi takes Retrofit as a parameter. Hilt is smart enough to see that, look at the other function in the same module, and provide the Retrofit instance automatically. It's a chain reaction.

Why is @Inject used in two different ways?

You'll see @Inject on constructors and @Inject on properties. They do very different things. Constructor injection is the gold standard. When you put it on a constructor, you're telling Hilt: "This is how you make this object, and here is what it needs."

class NewsRepository @Inject constructor(
    private val api: NewsApi
) { 
    // Hilt knows exactly how to provide NewsApi because of our Module
}

However, Android is weird. You don't instantiate your own Activity or Fragment; the Android OS does. Because you can't call the constructor yourself, you can't use constructor injection. That's where "Field Injection" comes in. You mark a variable with @Inject, and Hilt "plugs" the dependency in after the object is created.

@AndroidEntryPoint
class NewsActivity : AppCompatActivity() {

    @Inject lateinit var repository: NewsRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // By this point, Hilt has already assigned the repository
    }
}

Just a word of advice: avoid field injection whenever possible. Use it for Android components, but for your own internal logic classes, always stick to constructor injection. It makes your code much easier to unit test because you can just pass in a mock object without needing the whole Hilt framework running.




📋 Practical Task

Exercise: Wiring a Weather Data Repository with Hilt

You are building a weather app. You have a WeatherApi (interface) and a WeatherRepository (class). Currently, the WeatherActivity is manually instantiating everything, which is making the code messy.

Your task:

  • Create a WeatherModule using @Module and @InstallIn(SingletonComponent::class).
  • Add a @Provides method that returns a WeatherApi (you can mock the return value by returning a dummy implementation of the interface).
  • Update the WeatherRepository to use @Inject constructor so Hilt knows how to provide it.
  • Annotate WeatherActivity with @AndroidEntryPoint and use field injection to get the WeatherRepository instance.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.