Simple example of Dagger in Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyApp extends Application { | |
private ObjectGraph objectGraph; | |
public void onCreate() { | |
super.onCreate(); | |
objectGraph = ObjectGraph.create(new AppModule(this)); | |
} | |
public static void inject(Context context, Object toInject) { | |
MyApp app = (MyApp)context.getApplicationContext(); | |
app.objectGraph.inject(toInject); | |
} | |
public static void inject(Context context) { | |
inject(context, context); | |
} | |
} | |
@Module( | |
injects = { | |
FooActivity.class | |
} | |
) | |
public class AppModule { | |
private Context context; | |
public AppModule(Context context) { | |
this.context = context; | |
} | |
@Singleton @Provides | |
GSHTTPClient provideGSHTTPClient() { | |
return new GSHTTPClient(context); | |
} | |
} | |
public class FooActivity extends Activity { | |
@Inject | |
GSHTTPLib httpLib; | |
public void onCreate() { | |
super.onCreate(); | |
MyApp.inject(this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment