سؤال

I'm using Dagger for dependency injection in an Android application.

I have 2 application classes, let's call them A and B. B extends A extends android.app.Application

A has responsibilities and dependencies generic to any application. B has responsibilities and dependencies specific to the current application.

I'd like to be able to have 2 modules, AModule and BModule, with A injecting itself using the former and B the latter.

The problem is that it seems as if BModule must have a reference to A's class at compile-time, otherwise a runtime error is thrown. So this is what BModule has to look like to avoid the error (note the injects annotation field's value):

@Module(injects = {A.class}, library = true, complete = false)
public class BModule {
   ... 
}

But I would rather BModule only know about B, like this:

@Module(injects = {B.class}, library = true, complete = false)
public class BModule {
   ... 
}

The error thrown when I do this says, in effect, that the instance being injected (A) isn't of a class that BModule is known to be responsible for injecting.

Is there a way to achieve this that doesn't produce the runtime error?

Thanks!

هل كانت مفيدة؟

المحلول

Use module extension:

  public class A {
      @Inject 
      AA a;
  }

  public class B extends A {
      @Inject 
      BB b;
  }

And modules:

  @Module ( injects = A.class )
  public class AModule {
      @Provides
      public AA getAA() {
         return new AA();
      };
  }

  @Module ( overrides = true, includes = AModule.class, injects = B.class )
  public class BModule {
      @Provides
      public BB getBB() {
         return new BB();
      };
  }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top