{"id":17980920,"url":"https://github.com/nvidia/gontainer","last_synced_at":"2026-04-18T12:04:28.876Z","repository":{"id":192923988,"uuid":"684777481","full_name":"NVIDIA/gontainer","owner":"NVIDIA","description":"Simple but powerful dependency injection container for Go projects!","archived":false,"fork":false,"pushed_at":"2025-09-30T17:46:15.000Z","size":2599,"stargazers_count":66,"open_issues_count":0,"forks_count":5,"subscribers_count":3,"default_branch":"main","last_synced_at":"2026-04-05T06:33:27.663Z","etag":null,"topics":["dependency-injection","golang","service-container"],"latest_commit_sha":null,"homepage":"https://nvidia.github.io/gontainer/","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/NVIDIA.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-08-29T20:46:30.000Z","updated_at":"2026-03-25T21:37:33.000Z","dependencies_parsed_at":"2024-05-29T13:19:12.783Z","dependency_job_id":"3530b5fe-8b5f-422e-9aa0-d9bfc0277ec8","html_url":"https://github.com/NVIDIA/gontainer","commit_stats":null,"previous_names":["nvidia/gontainer"],"tags_count":30,"template":false,"template_full_name":null,"purl":"pkg:github/NVIDIA/gontainer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Fgontainer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Fgontainer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Fgontainer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Fgontainer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NVIDIA","download_url":"https://codeload.github.com/NVIDIA/gontainer/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Fgontainer/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31643431,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-10T07:40:12.752Z","status":"ssl_error","status_checked_at":"2026-04-10T07:40:11.664Z","response_time":98,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["dependency-injection","golang","service-container"],"created_at":"2024-10-29T18:06:56.113Z","updated_at":"2026-04-10T13:01:20.439Z","avatar_url":"https://github.com/NVIDIA.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n[![GoDoc](https://pkg.go.dev/badge/github.com/NVIDIA/gontainer/v2)](https://pkg.go.dev/github.com/NVIDIA/gontainer/v2)\n![Test](https://github.com/NVIDIA/gontainer/actions/workflows/go.yml/badge.svg)\n[![Report](https://goreportcard.com/badge/github.com/NVIDIA/gontainer/v2)](https://goreportcard.com/report/github.com/NVIDIA/gontainer/v2)\n\n# Gontainer\n\nSimple but powerful dependency injection container for Go projects!\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"splash.png\" width=\"600\"/\u003e\u003c/p\u003e\n\n## Features\n\n- 🎯 Automatic dependency injection based on function signatures.\n- ✨ Super simple interface to register and run services.\n- 🚀 Lazy service creation only when actually needed.\n- 🔄 Lifecycle management with proper cleanup in reverse order.\n- 🤖 Clean and tested implementation using reflection and generics.\n- 🧩 No external packages, no code generation, zero dependencies.\n\n## Quick Start\n\nThe example shows how to build the simplest app using service container.\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"log\"\n    \"github.com/NVIDIA/gontainer/v2\"\n)\n\n// Your services.\ntype Database struct{ connString string }\ntype UserService struct{ db *Database }\n\nfunc main() {\n    err := gontainer.Run(\n        context.Background(),\n        \n        // Register Database.\n        gontainer.NewFactory(func() *Database {\n            return \u0026Database{connString: \"postgres://localhost/myapp\"}\n        }),\n        \n        // Register UserService - Database is auto-injected!\n        gontainer.NewFactory(func(db *Database) *UserService {\n            return \u0026UserService{db: db}\n        }),\n        \n        // Use your services.\n        gontainer.NewEntrypoint(func(users *UserService) {\n            log.Printf(\"UserService ready with DB: %s\", users.db)\n        }),\n    )\n    \n    if err != nil {\n        log.Fatal(err)\n    }\n}\n```\n\n## Examples\n\n* [Console command example](./examples/01_console_command/main.go) – demonstrates how to build a simple console command.\n  ```\n  12:51:32 Executing service container\n  12:51:32 Hello from the Hello Service Bob\n  12:51:32 Service container executed\n  ```\n* [Daemon service example](./examples/02_daemon_service/main.go) – demonstrates how to maintain background services.\n  ```\n  12:48:22 Executing service container\n  12:48:22 Starting listening on: http://127.0.0.1:8080\n  12:48:22 Starting serving HTTP requests\n  ------ Application was started and now accepts HTTP requests -------------\n  ------ CTRL+C was pressed or a TERM signal was sent to the process -------\n  12:48:28 Exiting from serving by signal\n  12:48:28 Service container executed\n  ```\n* [Complete webapp example](./examples/03_complete_webapp/main.go) – demonstrates how to organize web application with multiple services.\n  ```\n  15:19:48 INFO msg=\"Starting service container\" service=logger\n  15:19:48 INFO msg=\"Configuring app endpoints\" service=app\n  15:19:48 INFO msg=\"Configuring health endpoints\" service=app\n  15:19:48 INFO msg=\"Starting HTTP server\" service=http address=127.0.0.1:8080\n  ------ Application was started and now accepts HTTP requests -------------\n  15:19:54 INFO msg=\"Serving home page\" service=app remote-addr=127.0.0.1:62640\n  15:20:01 INFO msg=\"Serving health check\" service=app remote-addr=127.0.0.1:62640\n  ------ CTRL+C was pressed or a TERM signal was sent to the process -------\n  15:20:04 INFO msg=\"Terminating by signal\" service=app\n  15:20:04 INFO msg=\"Closing HTTP server\" service=http\n  ```\n* [Transient service example](./examples/04_transient_services/main.go) – demonstrates how to return a function that can be called multiple times to produce transient services.\n  ```\n  11:19:22 Executing service container\n  11:19:22 New value: 8767488676555705225\n  11:19:22 New value: 5813207273458254863\n  11:19:22 New value: 750077227530805093\n  11:19:22 Service container executed\n  ```\n\n## Installation\n\n```bash\ngo get github.com/NVIDIA/gontainer/v2\n```\n\nRequirements: Go 1.21+\n\n## Core Concepts\n\n### 1. Define Services\n\nServices are just regular Go types:\n\n```go\ntype EmailService struct {\n    smtp string\n}\n\nfunc (s *EmailService) SendWelcome(email string) error {\n    log.Printf(\"Sending welcome email to %s via %s\", email, s.smtp)\n    return nil\n}\n```\n\n### 2. Register Factories\n\nFactories create your services. Dependencies are declared as function parameters:\n\n```go\n// Simple factory.\ngontainer.NewFactory(func() *EmailService {\n    return \u0026EmailService{smtp: \"smtp.gmail.com\"}\n})\n\n// Factory with dependencies - auto-injected!\ngontainer.NewFactory(func(config *Config, logger *Logger) *EmailService {\n    logger.Info(\"Creating email service\")\n    return \u0026EmailService{smtp: config.SMTPHost}\n})\n\n// Factory with a cleanup callback.\ngontainer.NewFactory(func() (*Database, func() error) {\n    db, _ := sql.Open(\"postgres\", \"...\")\n    \n    return db, func() error {\n        log.Println(\"Closing database\")\n        return db.Close()\n    }\n})\n```\n\n### 3. Run Container\n\n```go\nerr := gontainer.Run(\n    context.Background(),\n    gontainer.NewFactory(...),\n    gontainer.NewFactory(...),\n    gontainer.NewEntrypoint(func(/* dependencies */) {\n        // application entry point\n    }),\n)\n```\n\n## Advanced Features\n\n### Resource Cleanup\n\nReturn a cleanup function from your factory to handle graceful shutdown:\n\n```go\ngontainer.NewFactory(func() (*Server, func() error) {\n    server := \u0026http.Server{Addr: \":8080\"}\n    go server.ListenAndServe()\n    \n    // Cleanup function called on container shutdown.\n    return server, func() error {\n        ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n        defer cancel()\n        return server.Shutdown(ctx)\n    }\n})\n```\n\n### Optional Dependencies\n\nUse when a service might not be registered:\n\n```go\ngontainer.NewFactory(func(metrics gontainer.Optional[*MetricsService]) *API {\n    api := \u0026API{}\n    \n    // Use metrics if available\n    if m := metrics.Get(); m != nil {\n        api.metrics = m\n    }\n    \n    return api\n})\n```\n\n### Multiple Dependencies\n\nGet all services implementing an interface:\n\n```go\ntype Middleware interface {\n    Process(http.Handler) http.Handler\n}\n\ngontainer.NewFactory(func(middlewares gontainer.Multiple[Middleware]) *Router {\n    router := \u0026Router{}\n    for _, mw := range middlewares {\n        router.Use(mw)\n    }\n    return router\n})\n```\n\n### Dynamic Resolution\n\nResolve services on-demand:\n\n```go\ngontainer.NewEntrypoint(func(resolver *gontainer.Resolver) error {\n    // Resolve service dynamically.\n    var userService *UserService\n    if err := resolver.Resolve(\u0026userService); err != nil {\n        return err\n    }\n    \n    return userService.DoWork()\n})\n```\n\n### Transient Services\n\nCreate new instances on each call:\n\n```go\n// Factory returns a function that creates new instances.\ngontainer.NewFactory(func(db *Database) func() *Transaction {\n    return func() *Transaction {\n        return \u0026Transaction{\n            id: uuid.New(),\n            db: db,\n        }\n    }\n})\n\n// Use the factory function.\ngontainer.NewEntrypoint(func(newTx func() *Transaction) {\n    tx1 := newTx()  // new instance\n    tx2 := newTx()  // another new instance\n})\n```\n\n## API Reference\n\n### Module Functions\n\nGontainer module interface is really simple:\n\n```go\n// Run creates and runs a container with provided options.\nfunc Run(ctx context.Context, opts ...Option) error\n\n// NewFactory registers a service factory.\nfunc NewFactory(fn any) Option\n\n// NewService registers a pre-created service.\nfunc NewService[T any](service T) Option\n\n// NewEntrypoint registers an entrypoint function.\nfunc NewEntrypoint(fn any) Option\n```\n\n### Factory Signatures\n\n**Factory** is a function that creates one service. It can have dependencies as parameters,\nand can optionally return an error and/or a cleanup function for the factory.\n\n**Dependencies** are other services that the factory needs which are automatically injected.\n\n**Service** is a user-provided type. It can be any type except untyped `any`, context and `error`.\n\n\n```go\n// The simplest factory.\nfunc() *Service\n\n// Factory with dependencies.\nfunc(dep1 *Dep1, dep2 *Dep2) *Service\n\n// Factory with error.\nfunc() (*Service, error)\n\n// Factory with cleanup.\nfunc() (*Service, func() error)\n\n// Factory with cleanup and error.\nfunc() (*Service, func() error, error)\n```\n\n### Built-in Services\n\nGontainer provides several built-in services that can be injected into factories and functions.\nThey provide access to container features like context, dynamic resolution, and invocation.\n\n```go\n// context.Context - The factory's context.\nfunc(ctx context.Context) *Service\n\n// *gontainer.Resolver - Dynamic service resolution.\nfunc(resolver *gontainer.Resolver) *Service\n\n// *gontainer.Invoker - Dynamic function invocation.\nfunc(invoker *gontainer.Invoker) *Service\n```\n\n### Special Types\n\nGontainer provides special types for optional and multiple dependencies.\n\n```go\n// Optional[T] - Optional dependency declaration.\ntype Optional[T any] struct{}\nfunc (o Optional[T]) Get() T\n\n// Multiple[T] - Multiple services of the same interface.\ntype Multiple[T any] []T\n```\n\n## Error Handling\n\nGontainer provides typed errors for different failure scenarios:\n\n```go\nerr := gontainer.Run(ctx, factories...)\n\nswitch {\ncase errors.Is(err, gontainer.ErrFactoryReturnedError):\n    // Factory returned an error.\ncase errors.Is(err, gontainer.ErrEntrypointReturnedError):\n    // Entrypoint returned an error.\ncase errors.Is(err, gontainer.ErrNoEntrypointsProvided):\n    // No entrypoints were provided.\ncase errors.Is(err, gontainer.ErrCircularDependency):\n    // Circular dependency detected.\ncase errors.Is(err, gontainer.ErrDependencyNotResolved):\n    // Service type not registered.\ncase errors.Is(err, gontainer.ErrFactoryTypeDuplicated):\n    // Service type was duplicated.\n}\n```\n\n## Contributing\n\nWe welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n## License\n\nApache 2.0 – See [LICENSE](LICENSE) for details.\n\n## Documentation for `v1`\n\nDocumentation for the previous major version `v1` is available at [v1 branch](https://github.com/NVIDIA/gontainer/tree/v1).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnvidia%2Fgontainer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnvidia%2Fgontainer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnvidia%2Fgontainer/lists"}