Android
Injecting Dependencies into WorkManager Workers with Hilt
WorkManager creates workers through its own factory, which means constructor injection fails silently unless you replace that factory with Hilt's. This post covers @HiltWorker, @AssistedInject, and HiltWorkerFactory setup from scratch.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 1 of 8WorkManager in Production
- Injecting Dependencies into WorkManager Workers with Hilt
- WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
- Seeding a Room Database with a WorkManager Phased Dependency Graph
- A Base Worker Template for Batched Room Inserts with Retry and Progress
- Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
- Protecting Downloaded Files with a Rename-to-Backup Strategy
- Passing Structured Failure Data Out of a WorkManager Worker
- Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
WorkManager instantiates workers itself, bypassing the normal Hilt component
graph. If you annotate a worker constructor with @Inject and nothing else,
the app compiles, but WorkManager’s default factory can’t build the worker:
it looks for a (Context, WorkerParameters) constructor by reflection, fails
with NoSuchMethodException, logs “Could not instantiate” and the work fails
without ever running. The fix is @HiltWorker combined with @AssistedInject, which tells
Hilt that WorkManager provides two parameters (Context and WorkerParameters)
and Hilt provides the rest. This is the setup post for the entire WorkManager
series.
Prerequisites
Kotlin 2.0, Hilt 2.56, WorkManager 2.11.1, hilt-work 1.3.0, KSP 2.0.21-1.0.28.
Basic Hilt familiarity — @HiltAndroidApp, @AndroidEntryPoint, @Module —
is assumed.
Background
WorkManager uses its own WorkerFactory to instantiate workers. The default
factory creates workers using reflection with only two arguments: Context and
WorkerParameters. Any additional constructor parameters are unknown to it and
the construction fails.
Hilt solves this with HiltWorkerFactory, which replaces the default factory.
When WorkManager asks the factory to create a worker, Hilt injects all declared
dependencies through its component graph, with the two WorkManager-provided
arguments handled by @AssistedInject.
Implementation
1. Dependencies
dependencies { implementation(libs.hilt.android) ksp(libs.hilt.compiler)
implementation(libs.hilt.work) // "androidx.hilt:hilt-work:1.3.0" ksp(libs.hilt.ext.compiler) // "androidx.hilt:hilt-compiler:1.3.0"
implementation(libs.work.manager) // "androidx.work:work-runtime-ktx:2.11.1"}Both hilt-work and hilt-ext-compiler are required. hilt-ext-compiler
generates the @HiltWorker binding code at compile time. Missing it means
the generated factory entry for your worker is never created, so
HiltWorkerFactory has nothing to build it with.
2. Replace the default WorkManager factory
WorkManager initialises early in the app lifecycle via WorkManagerInitializer,
a Jetpack Startup component. It must be disabled so it does not start before
Hilt’s component is ready — otherwise HiltWorkerFactory is not yet available
when WorkManager first asks for it.
<provider android:name="androidx.startup.InitializationProvider" android:authorities="${applicationId}.androidx-startup" tools:node="merge"> <meta-data android:name="androidx.work.WorkManagerInitializer" android:value="@string/androidx_startup" tools:node="remove" /></provider>Then implement Configuration.Provider in your Application class:
@HiltAndroidAppclass App : Application(), Configuration.Provider {
@Inject lateinit var workerFactory: HiltWorkerFactory
override val workManagerConfiguration: Configuration get() = Configuration.Builder() .setWorkerFactory(workerFactory) .build()}Configuration.Provider tells WorkManager to use the configuration you return
from workManagerConfiguration instead of initialising with defaults. Hilt
injects HiltWorkerFactory into the Application class because
@HiltAndroidApp makes it an injection entry point.
3. Annotate the worker
Two annotations work together: @HiltWorker on the class, @AssistedInject
on the constructor, and @Assisted on the two WorkManager-managed parameters.
@HiltWorkerclass WritePartsToDatabase @AssistedInject constructor( @Assisted context: Context, @Assisted workParameters: WorkerParameters, private val partsDao: PartsDao, // injected by Hilt @StickyNotification notificationManager: NotificationManagerCompat, @StickyNotification notificationBuilder: NotificationCompat.Builder, progressRepository: ProgressRepository) : BaseWriteToDatabase( context, workParameters, notificationManager, notificationBuilder, progressRepository, notificationId = NotificationIds.PARTS) { override val fileName = "parts.json" override val resourceKey = "parts"
override suspend fun processFile(jsonFile: File): Int { /* ... */ }}@Assisted marks the parameters that WorkManager provides. Everything else —
partsDao, notificationManager, notificationBuilder, progressRepository —
is resolved from Hilt’s graph. Qualifiers (@StickyNotification) work normally
on Hilt-provided parameters.
4. Enqueue the worker
Nothing changes on the caller side. OneTimeWorkRequestBuilder<T> uses the
class token, WorkManager calls the factory, and HiltWorkerFactory resolves the
injection:
private inline fun <reified W : ListenableWorker> buildWorker(tag: String): OneTimeWorkRequest = OneTimeWorkRequestBuilder<W>() .addTag(tag) .setBackoffCriteria(BackoffPolicy.LINEAR, 1, TimeUnit.MINUTES) .build()Testing
TestListenableWorkerBuilder from work-testing creates a worker instance
in tests with explicit dependency injection — no Hilt graph required:
class TestFactory(private val dao: PartsDao, /* other fakes */) : WorkerFactory() { override fun createWorker( appContext: Context, workerClassName: String, workerParameters: WorkerParameters, ): ListenableWorker? = when (workerClassName) { WritePartsToDatabase::class.java.name -> WritePartsToDatabase(appContext, workerParameters, dao, /* ... */) else -> null // fall back to the default factory }}
val worker = TestListenableWorkerBuilder<WritePartsToDatabase>(context) .setWorkerFactory(TestFactory(fakeDao)) .build()
val result = worker.doWork()assertThat(result).isEqualTo(ListenableWorker.Result.success())For instrumented tests with a full Hilt graph, annotate the test class with
@HiltAndroidTest and inject the WorkManager instance directly.
Pitfalls
Production considerations
HiltWorkerFactory is backed by the SingletonComponent, which means all
@Singleton-scoped dependencies injected into workers live for the lifetime
of the process. This is correct for DAOs, repositories, and notification
managers. Do not inject @ActivityScoped or @ViewModelScoped objects into
workers — those scopes are shorter than the process lifetime and their
components may have been destroyed by the time a deferred worker runs.
Wrapping up
You now have a working Hilt + WorkManager integration: HiltWorkerFactory
replaces the default, @HiltWorker + @AssistedInject wires the constructor,
and the manifest entry prevents early initialisation. Every worker in the
series builds on this foundation.
Going deeper
What HiltWorkerFactory actually is. The hilt-compiler processor
generates an @AssistedFactory for each @HiltWorker and contributes it to a
Map<String, Provider<WorkerAssistedFactory<*>>> keyed by class name.
HiltWorkerFactory is a thin WorkerFactory that looks the class name up in
that map. That is why the lookup fails silently rather than at compile time:
the map simply has no entry.
Renamed or moved workers. WorkManager persists the worker’s fully
qualified class name in its database. If you rename or move a worker class and
users still have work enqueued under the old name, no factory can create it.
Either keep a small shim class at the old name or cancel the old work by tag
during a migration. A DelegatingWorkerFactory can also map the old name to
the new class.
Multi-module apps. In a modular app the worker can live in a feature
module, but the @HiltAndroidApp application must still see that module’s
generated bindings, so the feature module needs the same hilt-work and
hilt-compiler setup. The Configuration.Provider stays in the app module.
Initialisation cost. Removing the default initializer also means
WorkManager starts lazily, the first time you call getInstance(). That
shaves a little from cold start, and it is a good place to keep it: enqueue
the initial work after the first frame rather than in Application.onCreate().