如何在Dagger 2.16中为工人类实现Dagger?('android.arch.work:work-runtime') [英] How to implement Dagger for worker classes in Dagger 2.16 ?('android.arch.work:work-runtime')

查看:90
本文介绍了如何在Dagger 2.16中为工人类实现Dagger?('android.arch.work:work-runtime')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Dagger 2.16中为工人类实现Dagger?

How to implement Dagger for worker classes in Dagger 2.16?

public class SyncWorker extends  Worker {

    @Inject
    ISettingRepository settingRepository;

    @NonNull
    @Override
    public Result doWork() {

        sync();
        return Result.SUCCESS;
    }

    private void sync() {

    }
}

我的AppComponent

my AppComponent

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        BaseModule.class,
        ApiModule.class,
        UserDatabaseModule.class,
        SaleDatabaseModule.class,
        AppModule.class,
        ActivityBuilderModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
    void inject(BaseApp app);

    @Override
    void inject(DaggerApplication application);

    @Component.Builder
    interface Builder {
        @BindsInstance

        Builder getApp(Application application);

        AppComponent build();
    }

}

如何注入settingRepository?

How can I inject the settingRepository?

推荐答案

我能够用这种方法注入一个工人。

I was able to inject a worker with this approach.


  1. 首先,在您的应用程序组件内创建一个新方法,该方法将注入您的工作者类。

  1. First, create a new method inside your app component that will inject your worker class.

@Singleton
public interface AppComponent extends AndroidInjector<YourApplicationClass> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        AppComponent.Builder application(Application application);

        AppComponent build();
    }

    void inject(NotifWorker worker);
}      


  • 在您的应用程序内部,像往常一样构建匕首组件,但将其分配

  • Inside your application, build your dagger component as usual but assign it to a variable and make it global.

    public class YourApplicationClass implements HasActivityInjector {
    
      private AppComponent appComponent;
      @Override
      public void onCreate() {
          super.onCreate();
    
          appComponent = DaggerAppComponent.builder()
                  .application(this)
                  .build();
    
          appComponent.inject(this);
      }
    
      public AppComponent getAppComponent() {
          return appComponent;
      }
    }
    


  • 在您的工人阶级中,做类似的事情

  • Inside your worker class, do something like this.

    public class NotifWorker extends Worker {
    
      @Inject
      ToBeInjectedClass toBeInjectedClass;
    
      public NotifWorker() {
        YourApplicationClass
            .getInstance()
            .getAppComponent()
            .inject(this)
      }
    }
    


  • 这篇关于如何在Dagger 2.16中为工人类实现Dagger?('android.arch.work:work-runtime')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆