A lightweight, type-safe Dependency Injection (DI) container for Go, leveraging generics for a clean and intuitive API.
- Type-safe dependency registration and resolution using Go generics
- Support for both singleton and transient lifecycles
- Thread-safe operations
- No reflection for improved performance
- Simple and intuitive API
To install the Godi Engine, use go get
:
go get github.com/devs-group/godi
Here's a simple example of how to use the Godi Engine:
package main
import (
"fmt"
"github.com/devs-group/godi"
)
type Database struct {
ConnectionString string
}
type UserRepository struct {
DB *Database
}
type UserService struct {
Repo *UserRepository
}
func main() {
container := godi.New()
// Register services
godi.Register(container, func() *Database {
return &Database{ConnectionString: "example_connection_string"}
}, godi.Singleton)
godi.Register(container, func() *UserRepository {
db, _ := godi.Resolve[*Database](container)
return &UserRepository{DB: db}
}, godi.Transient)
godi.Register(container, func() *UserService {
repo, _ := godi.Resolve[*UserRepository](container)
return &UserService{Repo: repo}
}, godi.Transient)
// Resolve and use a service
userService, _ := godi.Resolve[*UserService](container)
fmt.Printf("Connection string: %s\n", userService.Repo.DB.ConnectionString)
}
container := godi.New()
godi.Register[T any](container *Container, constructor func() T, lifecycle Lifecycle)
container
: The DI containerconstructor
: A function that creates an instance of the servicelifecycle
: Eithergodi.Singleton
orgodi.Transient
service, err := godi.Resolve[T any](container *Container)
service := godi.MustResolve[T any](container *Container)
- Singleton: Only one instance is created and reused for all subsequent resolves.
- Transient: A new instance is created each time the service is resolved.
The Godi Engine is designed to be thread-safe. You can use a single container across multiple goroutines without worrying about race conditions.
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.