Dependency injection with Hilt

Part 2 ( Field injection )

Noha Samir
2 min readJul 6, 2020

Step 1. Inject dependencies into Android classes

Add @AndroidEntryPoint whenever you want to inject fields

Note: If you annotate an Android class with @AndroidEntryPoint, then you also must annotate Android classes that depend on it. For example, if you annotate a fragment, then you must also annotate any activities where you use that fragment.

// ToDo 1: Add @AndroidEntryPoint To inject fields in Fragment
@AndroidEntryPoint
class FirstFragment : Fragment() {
...
}
// ToDo 2: Add @AndroidEntryPoint to MainActivity that FirstFragment attached to it
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
...
}

Step 2. use the @Inject annotation to perform field injection

// ToDo 3: To inject a new instance of Car
// use the @Inject annotation to perform field injection
@Inject
lateinit var car: Car

Now we need to tell Hilt, How to create an instance for this field?

Step 3. Use the @Inject annotation on the constructor of a class

//ToDo 4 : Tell Hilt how to create instance by add @Inject annotation before constructor

class Car @Inject constructor(private val engine: Engine) {
...
}
/*
Now we tell hilt How to create Car but it doesn't know how to create Engine, if you run now you will see this error:
Engine cannot be provided without an @Inject constructor or an @Provides-annotated method
*/
//ToDo 5 : Tell Hilt how to create instance by add @Inject annotation before constructor
class
Engine @Inject constructor(){
...
}

Congratulations now you learn how to inject fields using Hilt

Get the code

Get the code from GitHub: (Link)

$ git clone https://github.com/NohaSamir/HiltApplication/tree/3-FieldInjection

Up Next: Part 3 / Part 1

--

--