我尝试了一个带有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
的自动生成的类......我是否必须自己使用它?
答案 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');
}));
});
});