title: Inject Application Context in Repository with Dagger 2
body: <p>I used the Dagger 2.17 to get the application context in the repository to access the resources:</p>
  <p>ContextInjection.kt:</p>
  <pre><code>@Module
  class ContextModule(private val context: Context) {
  
      @Singleton
      @Provides
      fun providesContext(): Context {
          return context
      }
  }
  
  @Singleton
  @Component(modules = [ContextModule::class])
  interface ContextComponent {
      fun inject(): Context
  }
  </code></pre>
  <p>Initialization.kt:</p>
  <pre><code>class Initialization : Application() {
  
      override fun onCreate() {
          super.onCreate()
  
          contextComponent = DaggerContextComponent.builder()
              .contextModule(ContextModule(this.applicationContext))
              .build()
      }
  
      companion object { // for access in repository
          lateinit var contextComponent: ContextComponent
      }
  }
  </code></pre>
  <p>Repository.kt:</p>
  <pre><code>@Singleton
  class Repository {
  
      @Inject
      lateinit var context: Context
  
      /** the method is invoked from view model class */
      fun loadList(pageIndex: Int): List&lt;String&gt; {
          context = Initialization.contextComponent.inject()
          val input = context.assets.open(&quot;tab1/item1/description.txt&quot;)
          ...
      }
  }
  </code></pre>
  <p>ViewModel.kt:</p>
  <pre><code>class PageViewModel : ViewModel() {
  
      @NonNull
      private val repository = Repository()
  
      private val pageIndex = MutableLiveData&lt;Int&gt;()
  
      val items = Transformations.map&lt;Int, List&lt;String&gt;&gt;(pageIndex) { index: Int -&gt;
          repository.loadList(index)
      }
  
      fun setIndex(index: Int) {
          pageIndex.value = index
      } 
  }
  </code></pre>
  <p>This works, but I have the next <strong>question</strong>:
  is there any other (better) way to get the context in the repository using a Dagger?</p>
  <p><strong>Note</strong>:
  I am confused by the static invoke:</p>
  <pre><code>context = Initialization.contextComponent.inject()
  </code></pre>
  <p>Not sure if this is good practice.</p>
  <p>Thank you for any answer/comment!</p>