-
Notifications
You must be signed in to change notification settings - Fork 3
Dependency Injection
ys-taylorchristie edited this page Nov 26, 2019
·
2 revisions
We use dependency injection in this project so we can easily test our service layer.
To use services inside Activities/Fragments you need to do the following.
Lets say we created a new activity/fragment ViewFriends
- Add your inject(ClassName className) entry into the
di/ServiceComponent.java
file:
void inject(ViewFriends viewFriends);
- In your
onCreate()
method in the activity, ensure you inject from the DI source before you call any injected variables:
protected void onCreate(Bundle savedStateBundle) {
super.onCreate(savedStateBundle);
ContextGrabber.get().di().inject(ViewFriends.this);
}
- Now above in your properties, you can easily inject dependencies. This is a full example.
class ViewFriends extends AppCompatActivity {
@Inject
AuthenticationService auth;
protected void onCreate(Bundle savedStateBundle) {
super.onCreate(savedStateBundle);
ContextGrabber.get().di().inject(ViewFriends.this);
// this will get the auth instance (which is a singleton) and output the username
Log.i("DI/TEST", auth.getUsername());
}
}
This eliminates the need to use new AuthenticationService() and allows you to use complex services (see: MoodEventService) without injecting a ton of dependencies manually.