{"id":31425149,"url":"https://github.com/michaelwp/go-inject","last_synced_at":"2025-09-30T04:57:33.688Z","repository":{"id":310221662,"uuid":"1039129581","full_name":"michaelwp/go-inject","owner":"michaelwp","description":"go dependency injection library","archived":false,"fork":false,"pushed_at":"2025-08-16T14:47:08.000Z","size":19,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-16T16:28:05.908Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/michaelwp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-16T14:44:09.000Z","updated_at":"2025-08-16T14:47:11.000Z","dependencies_parsed_at":"2025-08-16T16:39:14.054Z","dependency_job_id":null,"html_url":"https://github.com/michaelwp/go-inject","commit_stats":null,"previous_names":["michaelwp/go-inject"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/michaelwp/go-inject","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fgo-inject","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fgo-inject/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fgo-inject/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fgo-inject/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michaelwp","download_url":"https://codeload.github.com/michaelwp/go-inject/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fgo-inject/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":277632377,"owners_count":25850734,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-30T02:00:09.208Z","response_time":75,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-30T04:57:29.598Z","updated_at":"2025-09-30T04:57:33.682Z","avatar_url":"https://github.com/michaelwp.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Go-Inject 🚀\n\nA powerful, thread-safe dependency injection container for Go applications. Go-Inject provides a clean and intuitive API for managing dependencies with support for interfaces, generics, and multiple service lifetimes.\n\n## Features ✨\n\n- **Type-safe dependency injection** with Go generics support\n- **Interface-based registration** and resolution\n- **Multiple service lifetimes**: Singleton and Transient\n- **Thread-safe operations** with concurrent access support\n- **Automatic dependency resolution** with circular dependency detection\n- **Factory functions** with error handling\n- **Container injection** for advanced scenarios\n- **Clean, intuitive API** following Go best practices\n\n## Installation 📦\n\n```bash\ngo get github.com/go-inject/go-inject\n```\n\n## Quick Start 🚀\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/go-inject/go-inject\"\n)\n\ntype Logger interface {\n    Log(message string)\n}\n\ntype ConsoleLogger struct{}\n\nfunc (c *ConsoleLogger) Log(message string) {\n    fmt.Println(\"LOG:\", message)\n}\n\ntype UserService struct {\n    logger Logger\n}\n\nfunc (u *UserService) CreateUser(name string) {\n    u.logger.Log(fmt.Sprintf(\"Creating user: %s\", name))\n}\n\nfunc main() {\n    container := inject.NewContainer()\n\n    // Register interface implementation\n    inject.RegisterSingletonInterface[Logger, *ConsoleLogger](container, func(c *inject.Container) *ConsoleLogger {\n        return \u0026ConsoleLogger{}\n    })\n\n    // Register service with dependency\n    inject.RegisterTransientType[*UserService](container, func(c *inject.Container) *UserService {\n        logger := inject.MustResolve[Logger](c)\n        return \u0026UserService{logger: logger}\n    })\n\n    // Resolve and use service\n    userService := inject.MustResolve[*UserService](container)\n    userService.CreateUser(\"John Doe\")\n}\n```\n\n## Core Concepts 📚\n\n### Container\n\nThe `Container` is the central component that manages service registration and resolution:\n\n```go\ncontainer := inject.NewContainer()\n```\n\n### Service Lifetimes\n\n- **Singleton**: One instance per container, created on first request\n- **Transient**: New instance on every request\n\n### Registration Methods\n\n#### Basic Registration\n\n```go\n// Register with explicit lifecycle\ncontainer.Register((*MyService)(nil), func() *MyService {\n    return \u0026MyService{}\n}, inject.Singleton)\n\n// Convenience methods\ncontainer.RegisterSingleton((*MyService)(nil), func() *MyService {\n    return \u0026MyService{}\n})\n\ncontainer.RegisterTransient((*MyService)(nil), func() *MyService {\n    return \u0026MyService{}\n})\n```\n\n#### Generic Helpers\n\n```go\n// Type registration\ninject.RegisterSingletonType[*MyService](container, func(c *inject.Container) *MyService {\n    return \u0026MyService{}\n})\n\ninject.RegisterTransientType[*MyService](container, func(c *inject.Container) *MyService {\n    return \u0026MyService{}\n})\n\n// Interface registration\ninject.RegisterSingletonInterface[MyInterface, *MyImplementation](container, \n    func(c *inject.Container) *MyImplementation {\n        return \u0026MyImplementation{}\n    })\n\n// Value registration (always singleton)\nmyInstance := \u0026MyService{}\ninject.RegisterValue[*MyService](container, myInstance)\n```\n\n### Resolution Methods\n\n```go\n// Standard resolution with error handling\nservice, err := container.Resolve((*MyService)(nil))\nif err != nil {\n    // handle error\n}\n\n// Generic helper that panics on error\nservice := inject.MustResolve[*MyService](container)\n\n// Safe resolution that returns bool\nservice, ok := inject.TryResolve[*MyService](container)\nif !ok {\n    // service not found\n}\n```\n\n## Advanced Usage 🔧\n\n### Dependency Injection\n\nServices can automatically receive their dependencies:\n\n```go\ntype Database interface {\n    Query(sql string) []string\n}\n\ntype UserRepository struct {\n    db Database\n}\n\ntype UserService struct {\n    repo *UserRepository\n    logger Logger\n}\n\n// Register dependencies\ninject.RegisterSingletonInterface[Database, *MySQLDatabase](container, \n    func(c *inject.Container) *MySQLDatabase {\n        return \u0026MySQLDatabase{connectionString: \"...\"}\n    })\n\ninject.RegisterTransientType[*UserRepository](container, \n    func(c *inject.Container) *UserRepository {\n        db := inject.MustResolve[Database](c)\n        return \u0026UserRepository{db: db}\n    })\n\ninject.RegisterTransientType[*UserService](container, \n    func(c *inject.Container) *UserService {\n        repo := inject.MustResolve[*UserRepository](c)\n        logger := inject.MustResolve[Logger](c)\n        return \u0026UserService{repo: repo, logger: logger}\n    })\n```\n\n### Factory Functions with Error Handling\n\n```go\ncontainer.RegisterSingleton((*DatabaseConnection)(nil), func() (*DatabaseConnection, error) {\n    conn, err := sql.Open(\"mysql\", \"connection-string\")\n    if err != nil {\n        return nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n    }\n    return \u0026DatabaseConnection{conn: conn}, nil\n})\n```\n\n### Container Injection\n\nAccess the container within factory functions:\n\n```go\ninject.RegisterSingletonType[*ComplexService](container, \n    func(c *inject.Container) *ComplexService {\n        // Access other services through the container\n        if c.Has((*OptionalService)(nil)) {\n            optional := inject.MustResolve[*OptionalService](c)\n            return \u0026ComplexService{optional: optional}\n        }\n        return \u0026ComplexService{}\n    })\n```\n\n### Utility Methods\n\n```go\n// Check if service is registered\nif container.Has((*MyService)(nil)) {\n    // service is registered\n}\n\n// Get all registered service types\ntypes := container.GetServiceTypes()\nfor _, serviceType := range types {\n    fmt.Println(\"Registered:\", serviceType)\n}\n\n// Clear all registrations\ncontainer.Clear()\n```\n\n## Best Practices 💡\n\n### 1. Use Interfaces\n\nDefine and register interfaces rather than concrete types:\n\n```go\ntype Logger interface {\n    Log(message string)\n}\n\n// Good: Register interface\ninject.RegisterSingletonInterface[Logger, *ConsoleLogger](container, ...)\n\n// Avoid: Register concrete type directly\ninject.RegisterSingletonType[*ConsoleLogger](container, ...)\n```\n\n### 2. Choose Appropriate Lifetimes\n\n- Use **Singleton** for stateless services, configurations, and expensive resources\n- Use **Transient** for stateful services and lightweight objects\n\n```go\n// Singleton - shared state, expensive to create\ninject.RegisterSingletonInterface[Database, *MySQLDatabase](container, ...)\n\n// Transient - request-scoped, stateful\ninject.RegisterTransientType[*OrderProcessor](container, ...)\n```\n\n### 3. Handle Errors Gracefully\n\n```go\n// In production code, handle errors\nservice, err := container.Resolve((*CriticalService)(nil))\nif err != nil {\n    log.Fatalf(\"Failed to resolve critical service: %v\", err)\n}\n\n// Use MustResolve only when you're certain the service exists\nservice := inject.MustResolve[*KnownService](container)\n```\n\n### 4. Organize Registration\n\nCreate a setup function to organize your registrations:\n\n```go\nfunc SetupContainer() *inject.Container {\n    container := inject.NewContainer()\n    \n    // Infrastructure\n    registerDatabase(container)\n    registerLogging(container)\n    \n    // Repositories\n    registerRepositories(container)\n    \n    // Services\n    registerServices(container)\n    \n    return container\n}\n\nfunc registerDatabase(container *inject.Container) {\n    inject.RegisterSingletonInterface[Database, *MySQLDatabase](container, ...)\n}\n```\n\n## Error Handling 🚨\n\nThe library provides detailed error messages for common issues:\n\n- **Service not registered**: Clear message indicating which service type is missing\n- **Factory function errors**: Propagated from factory functions that return errors\n- **Type mismatches**: Validation during registration prevents runtime errors\n- **Circular dependencies**: Detected and reported with dependency chain\n\n## Thread Safety 🔒\n\nAll container operations are thread-safe:\n\n- Multiple goroutines can safely register services\n- Concurrent resolution is supported\n- Singleton instances are created safely with double-checked locking\n\n## Performance Considerations ⚡\n\n- **Service resolution**: O(1) lookup time\n- **Singleton creation**: One-time cost with lazy initialization\n- **Memory usage**: Minimal overhead, only stores service descriptors\n- **Concurrent access**: Optimized read-write locks for high concurrency\n\n## Testing 🧪\n\nThe library includes comprehensive test coverage. Run tests with:\n\n```bash\ngo test ./...\n```\n\n### Testing with Dependency Injection\n\n```go\nfunc TestUserService(t *testing.T) {\n    container := inject.NewContainer()\n    \n    // Register mock dependencies\n    inject.RegisterSingletonInterface[Logger, *MockLogger](container, \n        func(c *inject.Container) *MockLogger {\n            return \u0026MockLogger{}\n        })\n    \n    inject.RegisterTransientType[*UserService](container, \n        func(c *inject.Container) *UserService {\n            logger := inject.MustResolve[Logger](c)\n            return \u0026UserService{logger: logger}\n        })\n    \n    // Test the service\n    userService := inject.MustResolve[*UserService](container)\n    userService.CreateUser(\"Test User\")\n    \n    // Assert mock expectations...\n}\n```\n\n## Contributing 🤝\n\nContributions are welcome! Please read our contributing guidelines and submit pull requests to the main repository.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelwp%2Fgo-inject","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichaelwp%2Fgo-inject","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelwp%2Fgo-inject/lists"}