android도 규모가 좀 되는 것을 개발하다보면 필요성을 뼈저리게 느끼게 되는데, 가장 유명한 툴이 Dagger가 되겠다.
Dagger는 본래 Retrofit, okhttp 등으로 유명한 Square에서 공개한 라이브러리인데 google에서 fork한후 손을 봐서 Dagger2를 공개했다. dagger는 보다가 이해가 안되서 접었고 상대적으로 dagger2가 사용하기 쉬워서(?) 사용하고 있다.
instance를 constructor를 통해서 주입해주는 것이 기본인데,
android의 경우 constructor를 사용할 수 없는 경우가 있다.
바로 activity, fragment가 그 범인인데,
이경우에는 수동 inject를 해야 한다. 아래가 수많은 삽질 끝에 정리한, 그 수동 inject를 하는 Best Practice라고 생각한다.
사실은 조금 더 dagger2를 제대로 사용하려면, activity 혹은 fragment 단위에서 생성되는 instance들은 ActivityComponent와 Activity 단위의 scope를 도입해서 생명주기를 관리를 해야 한다.
This file contains hidden or 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
@Singleton | |
@Component( | |
modules = { | |
AppModule.class | |
}) | |
public interface ApplicationComponent { | |
void inject(MainActivity target); | |
final class Initializer { | |
private Initializer() {} | |
public static ApplicationComponent init(MyApplication app) { | |
return DaggerApplicationComponent.builder() | |
.appModule(new AppModule(app)) | |
.build(); | |
} | |
} | |
} |
This file contains hidden or 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
@Singleton | |
public class Dinner { | |
// codes... | |
} |
This file contains hidden or 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 MainActivity extends AppCompatActivity{ | |
@Inject | |
Dinner dinner; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
((MyApplication) getApplication()).getApplicationComponent().inject(this); | |
} | |
} |
This file contains hidden or 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 MyApplication extends Application { | |
private ApplicationComponent applicationComponent; | |
public ApplicationComponent getApplicationComponent() { | |
return applicationComponent; | |
} | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
applicationComponent = ApplicationComponent.Initializer.init(this); | |
} | |
} |