So from what I read, Dagger doesn\'t have support for inject in Worker yet. But there are some workarounds as people suggest. I have tried to do it a number of ways followin
In WorkManager alpha09 there is a new WorkerFactory that you can use to initialize the Worker the way you want to.
Worker constructor which takes in an ApplicationContext and WorkerParams.WorkerFactory via Configuration.configuration and register the newly created WorkerFactory.WorkManager with this configuration (while removing the ContentProvider which initializes WorkManager on your behalf).You need to do the following:
public DaggerWorkerFactory implements WorkerFactory {
@Nullable Worker createWorker(
@NonNull Context appContext,
@NonNull String workerClassName,
@NonNull WorkerParameters workerParameters) {
try {
Class extends Worker> workerKlass = Class.forName(workerClassName).asSubclass(Worker.class);
Constructor extends Worker> constructor =
workerKlass.getDeclaredConstructor(Context.class, WorkerParameters.class);
// This assumes that you are not using the no argument constructor
// and using the variant of the constructor that takes in an ApplicationContext
// and WorkerParameters. Use the new constructor to @Inject dependencies.
Worker instance = constructor.newInstance(appContext,workerParameters);
return instance;
} catch (Throwable exeption) {
Log.e("DaggerWorkerFactory", "Could not instantiate " + workerClassName, e);
// exception handling
return null;
}
}
}
// Create a configuration
Configuration configuration = new Configuration.Builder()
.setWorkerFactory(new DaggerWorkerFactory())
.build();
// Initialize WorkManager
WorkManager.initialize(context, configuration);