Reputation: 4021
I'm very new to Dagger 2 and I'm trying to get this basic example working with some minor modifications.
This is what I have so far:
Component class
@Component(modules = {MyModule.class})
public interface MyComponent {
void inject(Object object);
}
Module class
@Module
public class MyModule {
@Provides
@Singleton
public Retrofit getRetrofit(){
return new Retrofit();
}
}
Static Injector
public class MyStaticInjector {
private static MyComponent di;
public static void inject(Object object){
if(di == null){
di = DaggerMyComponent.builder().build();
}
di.inject(object);
}
}
The problem is that whenever I do
MyStaticInjector.inject(this);
the annotated fields are still null. I suspect the problem is with the type Object in the interface method. In the example, there's an Activity instead. But I need to use DI in classes that are not activities.
Can anyone help me? Thank you.
Upvotes: 0
Views: 2495
Reputation: 34542
Object
has no @Inject
annotated fields. Thus the injection works just fine—it just has nothing to inject.
You will have to use your actual classes with inject(MyClass)
instead of Object
, so that the code can be generated and fields can be injected.
Dagger generates source code at compile time. If it does not know about the actual class, it cannot create code for it.
Upvotes: 5