What is DI & Hilt?
According To Documentation, Dependency injection is a technique widely used in programming and well-suited to Android development. By following the principles of DI, you lay the groundwork for a good app architecture.
Implementing dependency injection provides you with the following advantages:
- Reusability of code
- Ease of refactoring
- Ease of testing
Hilt is an opinionated dependency injection library for Android that reduces the boilerplate of using manual DI in your project. Doing manual dependency injection requires constructing every class and its dependencies by hand and using containers to reuse and manage dependencies.
Hilt provides a standard way to do DI injection in your application by providing containers to every Android component in your project and managing the container's lifecycle automatically for you. This is done by leveraging the popular DI library: Dagger.
Let's Simplify DI
Let's think DI as a provider to assist you on get requested objects without explicitly creating new object at your own.
In the above diagram, we see that
Client asking for a dependency to the
Provider searching for the
Requested Object in the
Now, here is the magic. How do they do it? Is it really magic? Hmm?
No, it's logic.
Here is the process ::
- You register the required
Provider Repository, which would be provided to you as a
- When you request for the specific
Providersimply perform a search for the object in the
Repository, here is the fun fact - If you request for an
Objectthat is not properly registerd to the
Provider, Android Studio will
throw compile time error.
- So, simply think. You have a
Provider, who is responsible to provide you the requested depdency in
run-timeand the requested object should be
Let's talk about Dependency injection with Hilt
According to Official Documentation
Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project. Doing manual dependency injection requires you to construct every class and its dependencies by hand, and to use containers to reuse and manage dependencies.
Hilt provides a standard way to use DI in your application by providing containers for every Android class in your project and managing their lifecycles automatically. Hilt is built on top of the popular DI library Dagger to benefit from the compile-time correctness, runtime performance, scalability, and Android Studio support that Dagger provides. For more information, see Hilt and Dagger.
The most amazing things about DI/Hilt, is it's all about Annotation Processing.
What is Annotation Processing?
"Annotation Processing" is a hook into the compile process of the java compiler, to analyse the source code for user defined annotations and handle then (by producing compiler errors, compiler warning, emitting source code, byte code). Ref
That's it for today. In next part, we will dicuss about Hilt and it's implementation.