Dependency injection (DI) 是一种模式,其中对象从外部接收其依赖关系,而不是自己创建它们——提高了可测试性、可维护性和灵活性。在 Android 中,Hilt(建立在 Dagger 之上)是推荐的 DI 框架。
DI 是什么以及为什么
WITHOUT DI: a class CREATES its own dependencies (tightly coupled, hard to test/change):
class UserRepo { val api = ApiService() } // creates its own dependency — rigid
WITH DI: dependencies are PROVIDED from outside (injected):
class UserRepo(val api: ApiService) // receives it → flexible, testable
→ Benefits: TESTABILITY (inject mocks/fakes in tests), DECOUPLING, easier to swap
implementations, centralized dependency management, less boilerplate (with a framework).
