Golang Dependency Injection With karlkfi/inject
While investigating the pros and cons of manual ctor and IoC based dependency injection in go I looked at several IoC solutions:
I was astonished by karlkfi/inject how I was able to switch to an IoC with NO CHANGES WHATSOVER on my ctor DI based classes.
Check out the small changes yourself below or on github
Main features for me:
- no class attributes necessary
- Checkout
NewAutoProviderfor completely automatic constructor call creation - Checkout
NewProviderfor allowing to pass explicit parameters (like thedbcontext)
@@ -21,6 +21,7 @@
package main
import (
+ "github.com/karlkfi/inject"
"github.com/labstack/echo"
"github.com/ckolumbus/golangRestApiExampleWithDependencyInjection/pkg/employee/controller"
@@ -32,13 +33,20 @@ import (
)
func main() {
+ var (
+ employeePersist persistence.IEmployeePersist
+ employeeController *controller.EmployeeController
+ )
conn := db.SetupDB("sqlite3", "./db.sqlite")
defer conn.Close()
e := echo.New()
- employeePersist := persistence.NewEmployeePersist(conn)
- employeeController := controller.NewEmployeeController(employeePersist)
+ graph := inject.NewGraph(
+ inject.NewDefinition(&employeePersist, inject.NewProvider(persistence.NewEmployeePersist, &conn)),
+ inject.NewDefinition(&employeeController, inject.NewAutoProvider(controller.NewEmployeeController)),
+ )
+ graph.Resolve(&employeeController)
e.POST("/employee", employeeController.CreateEmployee)
e.DELETE("/employee/:id", employeeController.DeleteEmployee)