使用 Dagger2 将 DispatchingAndroidInjector<Service> 注入 App.kt

Inject DispatchingAndroidInjector<Service> into App.kt using Dagger2

我也尝试在处理接收通知的服务中使用依赖注入。

我遵循了 Nauce 的解决方案 https://github.com/googlesamples/android-architecture-components/issues/253

App.kt

class App : MultiDexApplication(), HasServiceInjector {

    @Inject lateinit var dispatchingServiceInjector: DispatchingAndroidInjector<Service>

    companion object {
        lateinit var applicationComponent: ApplicationComponent
    }

    override fun serviceInjector() = dispatchingServiceInjector

    override fun onCreate() {
        super.onCreate()

        applicationComponent = DaggerApplicationComponent
                .builder()
                .applicationModule(ApplicationModule(this))
                .build()
    }
}

MyOneSignalMessagingService.kt

@Singleton
class MyOneSignalMessagingService : NotificationExtenderService() {

    @Inject lateinit var ApiService: ApiService

    override fun onCreate() {
        super.onCreate()
        AndroidInjection.inject(this)
    }

  override fun onNotificationProcessing(notification: OSNotificationReceivedResult?): Boolean {
      // He i want to use ApiService
}

但是我不能在App.kt.

中注入dispatchingServiceInjector

MyOneSignalMessagingService收到通知时,它会抛出lateinit property dispatchingServiceInjector has not been initialized

您没有注入您的应用程序。注意 Nauce's example 中 ApplicationComponent 有这个方法:

@Component(/* ... */) @Singleton public interface AppComponent {
  /* ... */
  void inject(App app);
}

通过制作 returns void 的单参数方法,您定义了一个 members-injection method,它填充 @Inject-注释字段并调用 @Inject-现有对象实例上的注释方法。因为 Android 本身会创建您的 Application 实例,所以它不会自动填充其 @Inject 字段,因此您可以将其与您的组件一起注入。 (您通过调用 AndroidInjection.inject(this) 在服务和活动中执行相同的操作,但是因为您负责创建自己的组件实现,所以没有对应用程序的等效调用。)

在没有定义 AppInjector 的情况下,Nauce 在 onCreate 中调用它:

AppInjector.init(this);

但在您的示例中,在 App.kt:

中看起来更像这样
override fun onCreate() {
  super.onCreate()

  applicationComponent = DaggerApplicationComponent
      .builder()
      .applicationModule(ApplicationModule(this))
      .build()

  // Inject this class's @Inject-annotated members.
  applicationComponent.inject(this)
}

为了将来参考,您还可以选择从 DaggerApplication (in dagger.android or dagger.android.support), which would automatically provide all of your injectors as long as you make your ApplicationComponent extend AndroidInjector<App> and return it from the applicationInjector() method 扩展。