Dagger2: Unable to inject dependencies in WorkManager

前端 未结 4 937
庸人自扰
庸人自扰 2020-12-24 07:55

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

4条回答
  •  天涯浪人
    2020-12-24 08:26

    In WorkManager alpha09 there is a new WorkerFactory that you can use to initialize the Worker the way you want to.

    • Use the new Worker constructor which takes in an ApplicationContext and WorkerParams.
    • Register an implementation of WorkerFactory via Configuration.
    • Create a configuration and register the newly created WorkerFactory.
    • Initialize 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 workerKlass = Class.forName(workerClassName).asSubclass(Worker.class);
          Constructor 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);
    

提交回复
热议问题