go依賴注入庫samber/do使用示例講解
介紹
以簡單和高效而聞名的Go語言在其1.18版本中引入了泛型,這可以顯著減少大量代碼生成的需要,使該語言更加強大和靈活。如果您有興趣, Go 泛型教程 是很好的學(xué)習(xí)資源。
通過使用 Go 的泛型,samber/do庫為依賴注入 (DI) 提供了一個很好的解決方案。依賴注入是一種重要的設(shè)計模式,它促進對象及其依賴關(guān)系之間的松散耦合,從而提高代碼模塊化性、可測試性和可維護性。泛型和依賴注入的結(jié)合進一步提升了 Go 在創(chuàng)建高效、可擴展軟件方面的潛力。在本文中,您將學(xué)習(xí)如何使用 samber/do 提供依賴注入。
代碼結(jié)構(gòu)
. ├── cmd │ └── web │ └── main.go ├── domain │ └── user.go ├── go.mod ├── go.sum └── user ├── handler.go ├── repository.go └── service.go
我們使用與這篇博客相同的示例,但使用samber/do 庫來實現(xiàn) DI 而不是 Google Wire。正如我們所看到的,代碼的結(jié)構(gòu)變得更加簡單。您可以在 https://github.com/Shujie-Tan/do-example 找到源代碼。
服務(wù)關(guān)系
domain /user.go定義了業(yè)務(wù)邏輯結(jié)構(gòu)和接口,如下所示。
type ( User struct { ID string `json:"id"` Username string `json:"username"` } UserEntity struct { ID string Username string Password string } UserRepository interface { FetchByUsername(ctx context.Context, username string) (*UserEntity, error) } UserService interface { FetchByUsername(ctx context.Context, username string) (*User, error) } UserHandler interface { FetchByUsername() http.HandlerFunc } )
在用戶目錄下可以看到這些接口的實現(xiàn)。其關(guān)系可以表示為
UserHandler -> UserService -> UserRepository -> sql.DB
這意味著UserHandler依賴于UserService,而 UserService 又依賴于UserRepository,最后UserRepository依賴于sql.DB進行數(shù)據(jù)庫操作。這些依賴關(guān)系可通過使用接口來反轉(zhuǎn)。
這是一個很簡單的例子?,F(xiàn)在我們構(gòu)建對象及其依賴關(guān)系。
cmd/web/main.go
package main import ( "database/sql" "example/domain" "example/user" "fmt" "net/http" _ "github.com/lib/pq" "github.com/samber/do" ) func main() { injector := do.New() // 1 connStr := "user=root dbname=mydb" db, err := sql.Open("postgres", connStr) // 2 if err != nil { panic(err) } defer db.Close() do.ProvideNamed[*sql.DB](injector, "user", func(i *do.Injector) (*sql.DB, error) { return db, nil }) // 3 do.Provide(injector, user.NewRepository) do.Provide(injector, user.NewService) do.Provide(injector, user.NewHandler) // 4 userHandler := do.MustInvoke[domain.UserHandler](injector) // 5 http.Handle("/user", userHandler.FetchByUsername()) fmt.Printf("Try run server at :%d\n", 8080) if err := http.ListenAndServe(":8080", nil); err != nil { fmt.Printf("Error: %v", err) } }
我們逐步分析一下代碼:
- main 函數(shù)首先使用
injector := do.New()
創(chuàng)建一個新的 DI 容器。該容器將用于管理應(yīng)用程序?qū)ο蟮囊蕾囮P(guān)系。 - 使用
sql.Open
函數(shù)建立與 PostgreSQL 數(shù)據(jù)庫的連接。 - 使用
do.ProvideNamed
函數(shù)將數(shù)據(jù)庫連接添加到 DI 容器。 - 該函數(shù)采用三個參數(shù):DI 容器、依賴項的名稱以及返回依賴項和錯誤的提供程序函數(shù)。在本例中,依賴項是數(shù)據(jù)庫連接,該函數(shù)僅返回連接并返回 nil 來表示錯誤。使用
do.Provide
函數(shù)將repository、service和handler添加到 DI 容器。該函數(shù)有兩個參數(shù):DI 容器和返回依賴項和錯誤的函數(shù)。 - 在本例中,函數(shù)是
user.NewRepository
、user.NewService
和user.NewHandler
,它們分別創(chuàng)建repository、service和handler的實例。請注意提供程序函數(shù)的返回類型應(yīng)該是接口,而不是具體類型。Go語言模式『接受接口,返回結(jié)構(gòu)』將在 v2版本支持。使用do.MustInvoke
函數(shù)從 DI 容器檢索userHandler并將其注冊到 http 包。 - 該函數(shù)采用兩個參數(shù):DI 容器和要檢索的依賴項的類型。在本例中,它檢索用戶處理程序并將其FetchByUsername方法注冊為 /user 路由的處理程序。
用戶/repository.go
package user import ( "context" "database/sql" "example/domain" "github.com/samber/do" ) type repository struct { db *sql.DB } func (r *repository) FetchByUsername(ctx context.Context, username string) (*domain.UserEntity, error) { // use db here } // the return type of NewRepository should be interface, rather than the concrete type! func NewRepository(i *do.Injector) (domain.UserRepository, error) { db := do.MustInvokeNamed[*sql.DB](i, "user") return &repository{db: db}, nil }
user/service.go
package user import ( "context" "example/domain" "github.com/samber/do" ) type service struct { repo domain.UserRepository } func (s *service) FetchByUsername(ctx context.Context, username string) (*domain.User, error) { // use repository here } func NewService(i *do.Injector) (domain.UserService, error) { repo := do.MustInvoke[domain.UserRepository](i) return &service{repo: repo}, nil }
user/handler.go
package user import ( "example/domain" "net/http" "github.com/samber/do" ) type handler struct { svc domain.UserService } func (h *handler) FetchByUsername() http.HandlerFunc { // use service here } func NewHandler(i *do.Injector) (domain.UserHandler, error) { svc := do.MustInvoke[domain.UserService](i) return &handler{svc: svc}, nil }
結(jié)論
在本文中,我們學(xué)習(xí)了如何使用samber/do在 Go 中提供依賴注入。我們已經(jīng)了解了如何創(chuàng)建 DI 容器、向容器添加依賴項以及從容器中檢索依賴項。我們還了解了如何使用容器來管理應(yīng)用程序的依賴項。通過使用samber/do,我們可以創(chuàng)建更加模塊化、可測試和可維護的代碼,并充分利用 Go 的新泛型功能。
到此這篇關(guān)于go依賴注入庫samber/do使用示例講解的文章就介紹到這了,更多相關(guān)go依賴注入庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文帶你理解Golang中的Time結(jié)構(gòu)
根據(jù)golang的time包的文檔可以知道,golang的time結(jié)構(gòu)中存儲了兩種時鐘,一種是Wall?Clocks,一種是Monotonic?Clocks,下面我們就來簡單了解一下這兩種結(jié)構(gòu)吧2023-09-09詳解Go語言如何實現(xiàn)類似Python中的with上下文管理器
熟悉?Python?的同學(xué)應(yīng)該知道?Python?中的上下文管理器非常好用,那么在?Go?中是否也能實現(xiàn)上下文管理器呢,下面小編就來和大家仔細講講吧2023-07-07