Skip to content

Latest commit

 

History

History
46 lines (33 loc) · 7.03 KB

di.md

File metadata and controls

46 lines (33 loc) · 7.03 KB

Dependency Injection (DI)

DI 與 IoC 的差別??

Setter injection 有什麼不好??

  • Constructor Injection vs. Setter Injection (2009-02-19) http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/ 一開始可能會覺得 setter injection 比較好,尤其測試期間可以透過 setter 換成 test doubles。但 constructor injection 可以要求 initialization 的順序 (做為別人的 collaborator,自己要先完成 initialization)、可以避免 circular dependencies、可以將 collaborator field 設為 final 幫助理解它在 (object) lifetime 都不會變。反過來說,這就是 setter injection 的問題;setter injection 容易忘記呼叫 setter,什麼時候 wiring 才算完成也不清楚 (最後一個 setter call?)
  • Repeat After Me: Setter Injection is a Symptom of Design Problems - DZone Java (2012-06-15) https://dzone.com/articles/repeat-after-me-setter 如果發現 constructor injection 用起來不順手,通常反應了 design 上的問題;若真的遇到無法使用 constructor injection 的情境 (不是 design problem),可以把 setter injection 當做是個 workaround。
  • java - Why use constructor over setter injection in CDI? - Stack Overflow http://stackoverflow.com/questions/19381846/ #ril

代表目前使用者的 User 適合用 injection 注入嗎??

  • 總覺得 current user 與 database 裡的那個 user entity 是不同的?? 在 Android 上似乎不用規劃出一個 request scope,因為只有一個 user。
  • To “new” or not to “new”… http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/ 提到 newable (也就是 value object) 不適合由 injection framework 提供,但 user 算是 value object 嗎?? 或更精確地說是 "current user"
  • Dependency injection with Dagger 2 - Custom scopes – froger_mcs dev blog – Coding with love http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/ 提到 @UserScope,從系統架構來看,可以更方便取得 User instance 而不用透過 intent 傳遞,需要用到 user data 的人也可以直接從 constructor 要求 User
  • User object 似乎是個很特別的應用,像是個 configuration??
    • Java dependency injection: Injecting domain objects instead of infrastructure components (2014-11-10) http://www.mscharhag.com/java/dependency-injection-domain-objects 利用 scope 將 User domain object 直接注入;這和 Law of Demeter 多少有點關係 #ril
    • The Future of Dependency Injection with Dagger 2 - YouTube (2016-01-04) https://www.youtube.com/watch?v=plK0zyRLIP8 13:00 TwitterModule 的例子很有趣,因為需要一個 user name,所以要有一個明確的 constructor,這是把 (external) state 注入 graph 的方式。30:50 也提到定位在 @User scope 的 TwitterComponent,可以在使用者登出時整個丟棄 (GC),待下一個使用者登入時建立另一個 TwitterComponent
    • Dependency injection with Dagger 2 - Custom scopes – froger_mcs dev blog – Coding with love (2015-07-01) http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/ 在 application scope (@Singleton) 與 activity scope (@ActivityScope) 中間增加一層 user scope (@UserScope),方便直接從 constructor 注入 User

Assisted Injection

參考資料 {: #reference }