Dagger 2 Android应用程序组件缺少注入方法

时间:2017-03-21 12:39:35

标签: android dagger-2 dagger

我尝试了一个带有dagger.android包的新发布的Dagger 2.10的小型Android项目。 Dagger只应注入MainApplication类,其他任何依赖项都没有:

的build.gradle

dependencies {
  ...
  // Dagger
  compile 'com.google.dagger:dagger:2.10'
  compile 'com.google.dagger:dagger-android:2.10'
  annotationProcessor 'com.google.dagger:dagger-compiler:2.10'

  // Fix for incompatible library versions when adding dagger-android and having espresso-core:2.2.2 in tests
  androidTestCompile 'com.google.code.findbugs:jsr305:3.0.1'
}

MainApplication.java

public class MainApplication extends Application implements HasDispatchingActivityInjector {

  @Inject DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

  @Override
  public void onCreate() {
      super.onCreate();
      DaggerMainApplicationComponent.create();
   // DaggerMainApplicationComponent.create().inject(this); does not work - no inject(...) method!
  }

  @Override
  public DispatchingAndroidInjector<Activity> activityInjector() {
      return dispatchingAndroidInjector;
  }
}

MainApplicationComponent.java

@Component(modules = AndroidInjectionModule.class)
public interface MainApplicationComponent {}

自动生成的DaggerMainApplicationComponent.java:

public final class DaggerMainApplicationComponent implements MainApplicationComponent {
  private DaggerMainApplicationComponent(Builder builder) {
    assert builder != null;
  }

  public static Builder builder() {
    return new Builder();
  }

  public static MainApplicationComponent create() {
    return new Builder().build();
  }

  public static final class Builder {
    private Builder() {}

    public MainApplicationComponent build() {
      return new DaggerMainApplicationComponent(this);
    }
  }
}

我是Dagger的新手并且有很多资源,但很多人都在用过时的Dagger库描述DI。我的实施有什么问题? 我还发现了一个名为MainApplication_MembersInjector的自动生成的类......我是否必须自己使用它?

1 个答案:

答案 0 :(得分:0)

describe('ImageService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        ImageService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  afterEach(inject([XHRBackend], (mockBackend) => mockBackend.verifyNoPendingRequests()));

  describe('getPicture', () => {

    it('should call picture API', inject([ImageService, XHRBackend], (service: ImageService, mockBackend) => {
      mockBackend.connections.subscribe((connection) => {
          expect(connection.request.url).toBe('localhost/some/url/picture');
      });
      service.getPicture('id');
    }));

  });

});