Search code examples
androiddagger-2dagger-hilt

Dagger Hilt - What’s the point of @ApplicationContext and @ActivityContext?


In regards to @ApplicationContext and @ActivityContext in Hilt, I understand that they help to resolve ambiguity when a Context is being requested… but why not just request Application or Activity directly?


Solution

  • It depends on what you need, when you just need a context(call methods in the context class), then inject the context. If you really need an Activity, you can inject it to your class.

    But when you inject some class, it means your class depends on it and they are coupled. That's a bad practise in software design. When you inject an activity into your class, that means your class only works with that activity. If you inject an context, your class can work with any subclasses that implements the Context class