skip to content

In Hilt, how do you inject dependencies into a WorkManager worker and into a ContentProvider, two classes Hilt does not instantiate?

level: seniorimportance: should knowfreq 48%

answer

  1. who calls the constructor
  2. a factory WorkManager uses
  3. assisted Context and WorkerParameters
  4. an interface the component implements
  5. EntryPointAccessors matches @InstallIn

basics

~20 s

A worker gets @HiltWorker and an @AssistedInject constructor with @Assisted Context and WorkerParameters, and WorkManager is configured with the injected HiltWorkerFactory. A ContentProvider declares an @EntryPoint interface installed in SingletonComponent and reads it through EntryPointAccessors.fromApplication().

solid answer

~40 s

The two cases differ in who calls the constructor. WorkManager builds workers through a `WorkerFactory`, so Hilt's AndroidX extension supplies one: annotate the worker `@HiltWorker`, give it an `@AssistedInject` constructor whose `Context` and `WorkerParameters` are `@Assisted`, and make the `Application` implement `Configuration.Provider` with an injected `HiltWorkerFactory` passed to `setWorkerFactory`; because that replaces WorkManager's default configuration, remove its default initializer from the manifest. A worker can use only `@Singleton` or unscoped bindings. A `ContentProvider` is created by Android, and Hilt has no `@AndroidEntryPoint` support for it, so you pull dependencies instead: declare an `@EntryPoint` interface with one accessor per binding, `@InstallIn(SingletonComponent::class)`, and fetch it with `EntryPointAccessors.fromApplication(context, ...)`. The accessor must match the component the entry point is installed in.

code

kotlin · 15 lines
kotlin
@HiltWorker
class HeadlinesSyncWorker @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    private val repository: NewsRepository
) : CoroutineWorker(appContext, params) {

    override suspend fun doWork(): Result =
        try {
            repository.headlinesJson()
            Result.success()
        } catch (e: IOException) {
            Result.retry()
        }
}

go deeper

for a junior

Recall that workers use @HiltWorker and that classes Hilt cannot inject, such as a ContentProvider, use an @EntryPoint interface.

for a middle

Explain the @Assisted parameters, the HiltWorkerFactory configuration, and how an entry point's @InstallIn must match the accessor used to read it.

for a senior

Diagnose a worker that fails to instantiate and a ClassCastException from a mismatched entry point, and keep worker dependencies to singleton or unscoped bindings.

for a principal

Decide where entry points are acceptable, such as provider and library callbacks or dynamic feature modules, versus pushing code toward constructor injection.

## Two classes Hilt cannot construct or field-inject Hilt injects a class in one of two ways: it calls an `@Inject` constructor, or a generated `@AndroidEntryPoint` base class fills fields in a framework-created object. A **WorkManager worker** and a **`ContentProvider`** fit neither. WorkManager instantiates workers itself, through a `WorkerFactory`, and Android instantiates content providers from the manifest, a class Hilt does not list among its supported entry points. Hilt answers each case differently. ## Workers: `@HiltWorker` and `HiltWorkerFactory` The news app refreshes headlines in the background with a `HeadlinesSyncWorker` that needs the `NewsRepository`. Hilt's AndroidX extension makes WorkManager build it through Hilt. 1. Add the `androidx.hilt` work library and, alongside Hilt's own compiler, the `androidx.hilt` annotation processor, which works on top of it. 2. Annotate the worker class with **`@HiltWorker`** and its constructor with **`@AssistedInject`**. 3. Mark the two parameters WorkManager supplies, `Context` and `WorkerParameters`, with **`@Assisted`**. Every other parameter comes from Hilt's graph. 4. Make the `@HiltAndroidApp` application implement **`Configuration.Provider`**, inject a `HiltWorkerFactory` field, and return a `Configuration` built with `setWorkerFactory(workerFactory)`. 5. Because the app now supplies WorkManager's configuration, **remove WorkManager's default initializer** from the manifest, as WorkManager's custom-configuration guide describes. Two constraints follow from where the worker's dependencies are resolved: - A worker can use **only `@Singleton` or unscoped bindings**. There is no activity or ViewModel behind a background job, so `@ActivityScoped` or `@ViewModelScoped` bindings are not available to it. - If WorkManager still runs with its default factory, typically because the default initializer was left in place, that factory cannot call a constructor with a repository parameter, and the worker fails to be created. The worker's own API, constraints, retries and chaining belong to WorkManager; the assisted-injection mechanism underneath belongs to Dagger. What is Hilt-specific is the annotation pair and the factory wiring. ## Content providers: `@EntryPoint` An **entry point** is the boundary where code Hilt does not manage reaches into Hilt's graph. Technically it is an interface that the generated component implements. ```kotlin class OfflineArticlesProvider : ContentProvider() { @EntryPoint @InstallIn(SingletonComponent::class) interface ProviderEntryPoint { fun newsRepository(): NewsRepository } private fun repository(): NewsRepository = EntryPointAccessors.fromApplication( requireNotNull(context).applicationContext, ProviderEntryPoint::class.java ).newsRepository() // query(), insert() and the other ContentProvider overrides call repository() } ``` The rules that matter: - Declare **one accessor method per binding**, carrying the binding's qualifier if it has one. - `@InstallIn` on the interface picks the component, and the **accessor must match it**: `fromApplication` for `SingletonComponent`, `fromActivity`, `fromFragment` or `fromView` for those components. The general form is `EntryPoints.get(componentOrHolder, ...)`. - A mismatch is not caught by the compiler: the accessor casts the component to your interface, so an entry point installed in `ActivityComponent` but read with `fromApplication` throws `ClassCastException` at runtime. - Types returned by entry-point methods must be **public**, because the generated component, usually in another package, implements them. - Define the interface **next to the class that uses it**, not next to the type it returns; Dagger's guidance is that the entry point stands in for the missing `@Inject` constructor of its user. ## Failure modes and how to read them - **The worker is never created, so its work never runs**: WorkManager is still using its default factory, which cannot call a constructor with injected parameters. Check that the application implements `Configuration.Provider` with `HiltWorkerFactory` and that the default initializer is removed. - **A build error for a worker's dependency**: the worker asked for a binding outside the singleton graph, such as an activity-scoped one. - **`ClassCastException` from an entry point**: the accessor does not match the component in the interface's `@InstallIn`. - **A build error about visibility on an entry point**: a method returns an `internal` or package-private type. - **Forgotten `@Assisted`** on `Context` or `WorkerParameters`: Hilt would treat them as graph dependencies, but the graph binds neither an unqualified `Context` nor `WorkerParameters`, so the build fails with missing bindings. ## Which tool for which class | Class | Who constructs it | Hilt mechanism | |---|---|---| | Activity, fragment, view, service, receiver | Android | `@AndroidEntryPoint` field injection | | ViewModel | ViewModel factory | `@HiltViewModel` | | `Worker` / `CoroutineWorker` | WorkManager's `WorkerFactory` | `@HiltWorker` + `HiltWorkerFactory` | | `ContentProvider`, third-party callbacks | Android or a library | `@EntryPoint` + `EntryPointAccessors` | | Dynamic feature module code | not Hilt-processed | `@EntryPoint` feeding a hand-written Dagger component | That last row is the same idea at build scale: a dynamic feature module cannot be processed by Hilt, so the app module exposes an `@EntryPoint` interface and the feature builds a Dagger component that depends on it.

  • Why must the default WorkManager initializer be removed when you use HiltWorkerFactory?
    The default initializer sets WorkManager up at app startup with a default configuration, so your `Configuration.Provider` is never consulted. Removing it lets WorkManager initialise on demand from the application's provider, which carries the `HiltWorkerFactory`. Otherwise the default factory tries to build the worker and cannot satisfy its injected parameters.
  • Where should an @EntryPoint interface be declared, with the class that uses it or with the type it returns?
    With the class that uses it. The entry point replaces that class's missing `@Inject` constructor, so new dependencies become new methods on the same interface. Declaring it next to the returned type invites other code to use the entry point instead of normal injection.

  • Annotate the worker with @AndroidEntryPoint and Hilt will inject it.
  • A @HiltWorker can inject @ActivityScoped or @ViewModelScoped bindings.
  • Hilt's worker setup works without changing WorkManager's configuration.
  • EntryPointAccessors.fromApplication works for an entry point installed in any component.
  • A component mismatch on an entry point is reported at compile time.
  • An entry point's methods can return internal or private types.