Save 37% off PRO during our Black Friday Sale! »

DIコンテナを使わないDI / golang.tokyo#11

0f1d16574e6d15530b0e9e9b837d1d86?s=47 morikuni
December 11, 2017

DIコンテナを使わないDI / golang.tokyo#11

golang.tokyo#11の発表資料です。

スライド中のリンク
Github: https://github.com/morikuni
Twitter: https://twitter.com/inukirom
goldi: https://github.com/fgrosse/goldi
アドベントカレンダー: https://qiita.com/advent-calendar/2017/go4

0f1d16574e6d15530b0e9e9b837d1d86?s=128

morikuni

December 11, 2017
Tweet

Transcript

  1. DIίϯςφΛ࢖Θͳ͍DI golang.tokyo#11 2017/12/11

  2. ࣗݾ঺հ • Name: ৿ᅳ ହฏ (Morikuni Taihei) • GitHub: @morikuni

    • Twi9er: @inukirom • ॴଐ • גࣜձࣾϝϧΧϦ/ι΢κ΢ • ϝϧΧϦ Χ΢ϧ
  3. ຊ೔ͷ಺༰ ❌ DIͰ͖ΔΑ͏ʹίʔυΛॻ͘ํ๏ ⭕ DIίϯςφΛ࢖Θͣʹґଘؔ܎Λղܾ͢Δํ๏

  4. Ͳ͏΍ͬͯґଘؔ܎Λղܾ͢Δʁ • mainʹॻ͘ • DIίϯςφΛ࢖͏ • DI༻ͷؔ਺Λఆٛ͢Δ

  5. ྫ୊ ҎԼͷ3ͭͷؔ਺Λ࢖ͬͯServiceͷΠϯελϯεΛ࡞Εɻ func NewService(repo Repository, mailer Mailer) Service { ...

    } func NewRepository(db *sql.DB) Repository { ... } func NewMailer() Mailer { ... } Service͸RepositoryͱMailerʹґଘ͍ͯ͠Δɻ Repository͸*sql.DBʹґଘ͍ͯ͠Δɻ
  6. mainʹॻ͘ func main() { db, err := sql.Open("db", "dsn") if

    err != nil { ... } repo := NewRepository(db) mailer := NewMailer() service := NewService(repo, mailer) } ΦϒδΣΫτ͕૿͑Δ౓ʹmain͕ංେԽ͍͖ͯ͠Մಡੑ͕௿͍
  7. DIίϯςφΛ࢖͏ (goldi*1) • yamlʹґଘؔ܎Λهड़͢Δ • DIίϯςφ༻ͷίʔυΛੜ੒͢Δ • DIίϯςφ͔ΒඞཁͳΠϯελϯεΛऔಘ͢Δ DIίϯςφͷ࢖͍ํΛ֮͑Δඞཁ͕͋Δ *1

    ࣮ࡍʹgoldiΛ࢖ͬͨ͜ͱ͸ͳ͍ͷͰؒҧ͍ͬͯΔՄೳੑ͕͋Γ·͢
  8. types: db: package: database/sql type: *DB factory: Open arguments: -

    "db" - "dsn" repository: package: github.com/morikuni/hoge type: Repository factory: NewRepository arguments: - "@db" mailer: package: github.com/morikuni/hoge type: Mailer factory: NewMailer service: package: github.com/morikuni/hoge type: Service factory: NewService arguments: - "@repository" - "@mailer"
  9. DI༻ͷؔ਺Λఆٛ͢Δ(Injectؔ਺) • ΦϒδΣΫτ͕Ҿ਺0ݸͰऔಘͰ͖ΔΑ͏ʹ͢Δؔ਺ • ͋ΔΦϒδΣΫτʹ͍ͭͯɺґଘઌ͕Ҿ਺0ݸͰऔಘͰ͖Ε͹ͦ ͷΦϒδΣΫτ΋Ҿ਺0ݸͰऔಘͰ͖Δ • Injectؔ਺Λ૊Έ߹ΘͤΔ͜ͱͰInjectؔ਺Λ࡞Δ

  10. Injectؔ਺ͷ࣮૷ InjectDB͸*sql.DB͕Ҿ਺0ݸͰऔಘͰ͖ΔΑ͏ʹ͢Δ func InjectDB() *sql.DB { db, err := sql.Open("db",

    "dsn") if err != nil { panic(err) } return db }
  11. Injectؔ਺ͷ࣮૷ *sql.DB͕Ҿ਺0ݸͰऔಘͰ͖ΔͷͰRepository΋Ҿ਺0ݸͰऔಘͰ͖Δ func InjectRepository() Repository { return NewRepository( InjectDB(), )

    } func InjectMailer() Mailer { return NewMailer() }
  12. Injectؔ਺ͷ࣮૷ RepositoryͱMailer͕Ҿ਺0ݸͰऔಘͰ͖ΔͷͰɺService΋ Ҿ਺0ݸͰऔಘͰ͖ΔΑ͏ʹͳΔ func InjectService() Service { return NewService( InjectRepository(),

    InjectMailer(), ) }
  13. Injectؔ਺Λ࢖͏ར఺ • ґଘઌ͕૿ݮͨ͠ͱͯ͠΋Өڹൣғ͸Injectؔ਺಺ʹऩ·Δ • ࣮૷͕ॻ͔ΕΔpackage͕มΘͬͯ΋Өڹൣғ͸Injectؔ਺಺ʹ ऩ·Δ • GoͷίʔυͰॻ͚ΔͷͰߏจΛ৽֮͑͘͠Δඞཁ͕ͳ͍

  14. ৄ͘͠͸WebͰʂ ໌೔(12/12)ͷQiita Advent Calender Go4ʹ ΋͏গ͠ৄ͍͠هࣄΛॻ͖·͢ʂ h"ps:/ /qiita.com/advent-calendar/2017/go4