Gin实现依赖注入

前言#

依赖注入的好处和特点这里不讲述了,本篇文章主要介绍gin框架如何实现依赖注入,将项目解耦。

项目结构#

Copy
├── cmd 程序入口 ├── common 通用模块代码 ├── config 配置文件 ├── controller API控制器 ├── docs 数据库文件 ├── models 数据表实体 ├── page 页面数据返回实体 ├── repository 数据访问层 ├── router 路由 ├── service 业务逻辑层 ├── vue-admin Vue前端页面代码

相信很多Java或者.NET的码友对这个项目结构还是比较熟悉的,现在我们就用这个项目结构在gin框架中实现依赖注入。这里主要介绍controller、service和repository。

数据访问层repository#

  1. 首先定义IStartRepo接口,里面包括Speak方法
Copy
//IStartRepo 定义IStartRepo接口 type IStartRepo interface { Speak(message string) string }
  1. 实现该接口,这里就不访问数据库了,直接返回数据
Copy
//StartRepo 注入数据库 type StartRepo struct { Source datasource.IDb `inject:""` } //Speak 实现Speak方法 func (s *StartRepo) Speak(message string) string { //使用注入的IDb访问数据库 //s.Source.DB().Where("name = ?", "jinzhu").First(&user) return fmt.Sprintf("[Repository] speak: %s", message) }

这样我们就简单完成了数据库访问层的接口封装

业务逻辑层service#

  1. 定义IStartService接口
Copy
//IStartService 定义IStartService接口 type IStartService interface { Say(message string) string }
  1. 实现IStartService接口方法,注入IStartRepo数据访问层
Copy
//StartService 注入IStartRepo type StartService struct { Repo repository.IStartRepo `inject:""` } //Say 实现Say方法 func (s *StartService) Say(message string) string { return s.Repo.Speak(message) }

控制器controller#

  1. 注入IStartService业务逻辑层,并调用Say方法
Copy
//Index 注入IStartService type Index struct { Service service.IStartService `inject:""` } //GetName 调用IStartService的Say方法 func (i *Index) GetName(ctx *gin.Context) { var message = ctx.Param("msg") ctx.JSON(200, i.Service.Say(message)) }

注入gin中#

到此三个层此代码已写好,然后我们使用"github.com/facebookgo/inject"Facebook的工具包将它们注入到gin中。

Copy
func Configure(app *gin.Engine) { //controller declare var index controller.Index //inject declare db := datasource.Db{} //Injection var injector inject.Graph err := injector.Provide( &inject.Object{Value: &index}, &inject.Object{Value: &db}, &inject.Object{Value: &repository.StartRepo{}}, &inject.Object{Value: &service.StartService{}}, ) if err != nil { log.Fatal("inject fatal: ", err) } if err := injector.Populate(); err != nil { log.Fatal("inject fatal: ", err) } //database connect err = db.Connect() if err != nil { log.Fatal("db fatal:", err) } v1 := app.Group("/") { v1.GET("/get/:msg", index.GetName) } }

有关更多的github.com/facebookgo/inject使用方法请参考文档

本demo源码地址:https://github.com/Bingjian-Zhu/gin-inject

posted @   烟花易冷人憔悴  阅读(4129)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示
CONTENTS