룬아님의 취중코딩

(Dagger2) Service에서 dagger 사용하기 본문

개발/안드로이드 개발

(Dagger2) Service에서 dagger 사용하기

룬아님 2019. 12. 31. 16:41

1. 서비스에 주입할 모듈 작성

@Module
abstract class ServiceBuilderModule {

    @ContributesAndroidInjector
    abstract MyService contributeMyService();

}

 

2. Application Component에 모듈 등록

@Component(modules = {
        AndroidSupportInjectionModule.class,
        AppModule.class,
        ActivityBuilderModule.class,
        ServiceBuilderModule.class
})
@Singleton
public interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(App application);

        AppComponent build();
    }

    void inject(App app);

}

 

3. onCreate에서 AndroidInjection.inject(this) 호출

public class MyService extends Service {

    @Inject
    InjectClass injectClass;

    @Override
    public void onCreate() {
        AndroidInjection.inject(this);
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
}
반응형
Comments