在golang框架中实现依赖注入的最佳实践-Golang

首页 2024-07-03 21:44:26

Go 依赖注入的最佳实践在框架中实现

依赖注入 (DI),它是一种设计模式,允许在运行过程中将依赖传递给对象,而不是在创建对象时指定显式。DI 在 Go 框架非常有用,可以提高代码的可测试性、可维护性和灵活性。

使用框架

有许多 Go 框架提供了 DI 支持,例如 Wire 和 Gin。这些框架提供定义和注入依赖项的函数和注释。

立即学习"go语言免费学习笔记(深入);

使用 Wire

Wire 它很受欢迎 Go DI 框架。使用 Wire 实现 DI 如下:

package main

import "<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15841.html" target="_blank">git</a>hub.com/google/wire"

type Service struct {
    Repo *Repository
}

func NewService(repo *Repository) *Service {
    return &Service{Repo: repo}
}

type Repository struct{}

var wireSet = wire.NewSet(wire.Struct(new(Service), "*"), wire.Struct(new(Repository), "*"))

func main() {
    wire.Build(wireSet)
}

使用 Gin

Gin 是一个 Go Web 框架。使用 Gin 实现 DI 如下:

package main

import "github.com/gin-gonic/gin"

type Service struct {
    Repo *Repository
}

func NewService(repo *Repository) *Service {
    return &Service{Repo: repo}
}

type Repository struct{}

func main() {
    r := gin.New()
    repo := &Repository{}
    service := NewService(repo)
    r.GET("/", func(c *gin.Context) {
        // Use the service
        _ = service
    })
    r.Run()
}

接口和抽象

可重用和可测试的接口和抽象可以创建 DI 代码。例如:

type UserRepository interface {
    GetUser(id int) (*User, error)
}

type UserService struct {
    Repo UserRepository
}

测试

使用 DI 框架可以很容易地测试依赖项。例如:

package main

import (
    "github.com/google/wire"
    "testing"
)

func TestService(t *testing.T) {
    type MockRepo struct {
        GetUserFunc func(int) (*User, error)
    }

    wire.Build(
        wire.NewSet(
            wire.Struct(new(Service), "*"),
            wire.Value(
                &MockRepo{
                    GetUserFunc: func(id int) (*User, error) {
                        return &User{}, nil
                    },
                },
            ),
        ),
    )
    // Test the Service
}

以上是golang框架中依赖注入的最佳实践的详细内容。请关注其他相关文章!


p
MySQL连接就这么简单!本地远程、编程语言连接方法一网打尽
还在为MySQL日期计算头疼?这份加一天操作指南能解决90%问题
MySQL日志到底在哪里?Linux/Windows/macOS全平台查找方法在此
MySQL数据库管理工具全景评测:从Workbench到DBeaver的技术选型指南
MySQL密码忘了怎么办?这份重置指南能救急,Windows/Linux/Mac都适用
你的MySQL为什么经常卡死?可能是锁表在作怪!快速排查方法在此
MySQL单表卡爆怎么办?从策略到实战,一文掌握「分表」救命技巧
清空MySQL数据表千万别用错!DELETE和TRUNCATE这个区别可能导致重大事故
你的MySQL中文排序一团糟?记住这几点,轻松实现准确拼音排序!
别再混淆Hive和MySQL了!读懂它们的天壤之别,才算摸到大数据的门道