How to integrate Dagger 2 with other Android components?

Dagger 2 is a popular dependency injection framework for Android. Integrating Dagger 2 with other Android components, such as Activities, Fragments, and Services, allows for better code organization and easier management of dependencies.

Integrating Dagger 2 with Activities

To integrate Dagger 2 with an Activity, follow these steps:

  1. Create a Component interface that includes your Activity as a module.
  2. Use the @Inject annotation in your Activity to specify the dependencies you need.
  3. Call the Dagger component to inject the dependencies in your Activity's onCreate() method.

Example:

@Module class MainActivityModule { @Provides fun provideGreeting(): String { return "Hello, Dagger!" } } @Component(modules = [MainActivityModule::class]) interface MainActivityComponent { fun inject(activity: MainActivity) } class MainActivity : AppCompatActivity() { @Inject lateinit var greeting: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DaggerMainActivityComponent.create().inject(this) Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show() } }

Integrating Dagger 2 with Fragments

The integration process for Fragments is similar:

  1. Create a Fragment component and module.
  2. Inject dependencies in the Fragment using @Inject.
  3. Use the Dagger component to inject in the Fragment's onCreateView() method.

Example:

@Module class FragmentModule { @Provides fun provideDependency(): SomeDependency { return SomeDependency() } } @Component(modules = [FragmentModule::class]) interface FragmentComponent { fun inject(fragment: MyFragment) } class MyFragment : Fragment() { @Inject lateinit var dependency: SomeDependency override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { DaggerFragmentComponent.create().inject(this) // Use dependency... return inflater.inflate(R.layout.fragment_layout, container, false) } }

Dagger 2 Dependency Injection Android Integration Activities Fragments Components