2017-09-01 48 views
0

我想讓匕首在我的應用程序工作。 創建模塊組件和MyApp後,我可以使用匕首將數據庫服務注入到視圖中,但我無法與演示者一起做同樣的事情。 代碼:我怎麼能注入對象到android kotlin MVP mosby應用程序的主持人匕首

class MyApp : Application() { 

    var daoComponent: DaoComponent? = null 
    private set 

    override fun onCreate() { 
     super.onCreate() 

     daoComponent = DaggerDaoComponent.builder() 
      .appModule(AppModule(this)) // This also corresponds to the name of your module: %component_name%Module 
      .daoModule(DaoModule()) 
      .build() 
    } 
} 

模塊

@Module 
class DaoModule { 
    @Provides 
    fun providesEstateService(): EstateService = EstateServiceImpl() 
} 

元器件

@Singleton 
@Component(modules = arrayOf(AppModule::class, DaoModule::class)) 
interface DaoComponent { 
    fun inject(activity: MainActivity) 
} 

的AppModule

@Module 
class AppModule(internal var mApplication: Application) { 

    @Provides 
    @Singleton 
    internal fun providesApplication(): Application { 
     return mApplication 
    } 
} 

MainActivity

class MainActivity : MvpActivity<MainView, MainPresenter>(), MainView { 
    @Inject 
    lateinit var estateService : EstateService 

    override fun onCreate(savedInstanceState: Bundle?) { 
     super.onCreate(savedInstanceState) 
     setContentView(R.layout.activity_main) 
     (application as MyApp).daoComponent!!.inject(this)estateService.numberOfInvoicedEstates.toString() 
    } 

    override fun createPresenter(): MainPresenter = MainPresenterImpl() 
} 

注入estateService這種方式後,我可以使用它,但我無法弄清楚如何直接注入服務的演示者。 我試過這樣做,但它不工作。 我應該只是從活動中傳入注入的對象嗎?或者也許我應該通過MyApp作爲參數或使靜態方法允許我從應用程序中的任何位置獲取它?

class MainPresenterImpl 
    @Inject 
    constructor(): MvpBasePresenter<MainView>(),MainPresenter { 
     @Inject 
     lateinit var estateService : EstateService 
} 

回答

1

你的組件應該提供這樣的主持人:

@Component(modules = arrayOf(AppModule::class, DaoModule::class)) 
@Singleton 
interface MyComponent { 
    mainPresenter() : MainPresenter 
} 

而且所有依賴性的主持人需要通過構造函數參數注入主持人:

class MainPresenterImpl 
    @Inject constructor(private val estateService : EstateService) : 
    MvpBasePresenter<MainView>(),MainPresenter { 
    ... 
} 

createPresenter()剛剛搶主持人來回m匕首組件如下:

class MainActivity : MvpActivity<MainView, MainPresenter>(), MainView { 

    ... 

    override fun createPresenter(): MainPresenter = 
     (application as MyApp).myComponent().mainPresenter() 
} 

請注意,上面顯示的代碼不會編譯。這只是僞代碼,可以讓您瞭解依賴圖在Dagger中的樣子。

+0

這是我正在尋找的答案。謝謝 – Piotr

0

請參考this例如如何結合使用MVP匕首2。

0

你必須告訴你的組件在哪裏你要注入它。

所以,儘量與此組件:

@Singleton 
@Component(modules = arrayOf(AppModule::class, DaoModule::class)) 
interface DaoComponent { 
    fun inject(presenter: MainPresenterImpl) 
}