Documentation
¶
Overview ¶
Example ¶
Example demonstrates basic usage of the bind dependency injection container
package main
import (
"fmt"
"github.com/mlctrez/bind"
)
// Database represents a database connection with lifecycle management
type Database struct {
ConnectionString string
connected bool
}
func (db *Database) Startup() error {
fmt.Printf("Connecting to database: %s\n", db.ConnectionString)
db.connected = true
return nil
}
func (db *Database) Shutdown() error {
fmt.Println("Disconnecting from database")
db.connected = false
return nil
}
type User struct {
Name string
}
func (db *Database) GetUser(id int) (*User, error) {
return &User{Name: fmt.Sprintf("User %d", id)}, nil
}
// UserService depends on Database
type UserService struct {
DB *Database
}
func (us *UserService) Startup() error {
fmt.Println("UserService starting up")
return nil
}
func (us *UserService) GetUser(id int) string {
user, err := us.DB.GetUser(id)
if err != nil {
return ""
}
return user.Name
}
func main() {
// Create a new binder
binder := bind.New()
// Create and configure dependencies
db := &Database{ConnectionString: "postgres://localhost/mydb"}
userService := &UserService{}
// Add all components to the binder
// Dependencies will be automatically injected based on type matching
if err := binder.Add(db, userService); err != nil {
panic(err)
}
// Use the service (dependencies are already injected and started up)
user := userService.GetUser(123)
fmt.Printf("Retrieved: %s\n", user)
// Clean shutdown - calls Shutdown() on all components in reverse order
binder.Shutdown()
}
Output: Connecting to database: postgres://localhost/mydb UserService starting up Retrieved: User 123 Disconnecting from database
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Binder ¶
type Binder interface {
// Add registers one or more items for dependency injection.
// Items must be pointers to structs or other types.
Add(items ...any) error
// Shutdown calls Shutdown() on all registered items in reverse order.
Shutdown()
}
Binder provides dependency injection with lifecycle management. Items are registered as pointers and dependencies are automatically injected into struct fields based on type matching.
Click to show internal directories.
Click to hide internal directories.