Context-based dependency management for Go - simple, type-safe, and test-friendly.
Go already has a nice way to keep track of things with context.Context. This library adds helpers to simplify getting things out of that context, with support for lazy initialization, caching, and clean testing patterns.
go get github.com/gburgyan/go-ctxdeptype UserService struct {
// ...
}
func main() {
ctx := ctxdep.NewDependencyContext(context.Background(), &UserService{})
handleRequest(ctx)
}
func handleRequest(ctx context.Context) {
svc := ctxdep.Get[*UserService](ctx)
// use svc...
}- Simple interface built on Go's
context.Context - Type-safe access to dependencies
- Thread-safe with no deadlock risks
- Fail-fast - errors surface immediately, not in production
- Fast dependency resolution
- Explicit over magic - no hidden configuration
- Easy testing - the main motivation for this library
Full documentation is available in the docs/ directory:
- Getting Started - Installation and quick start
- Core Concepts - How context dependencies work
- Generators - Lazy dependency creation
- Testing - Why this makes testing easy
- Adapters - Partial function application
- Caching - Cache expensive operations
- Validation - Validate during context creation
- Lifecycle - Resource cleanup
- Context Control - Locking and overrides
- Optional Dependencies - Graceful handling
- Advanced Topics - Thread safety, debugging, timing
- Design Decisions - Architecture rationale
Testing. Testing is what started the idea for this.
Without a way to manage dependencies through context, overriding them in tests is awkward:
// Hard to test - how do you mock GetUserData?
func isPermitted(request *Request) bool {
userData := user.GetUserData(request.userId)
return userData.IsAdmin
}With go-ctxdep:
func isPermitted(ctx context.Context) bool {
user := ctxdep.Get[*UserData](ctx)
return user.IsAdmin
}
func Test_isPermitted(t *testing.T) {
ctx := ctxdep.NewDependencyContext(context.Background(),
&UserData{IsAdmin: true},
)
assert.True(t, isPermitted(ctx))
}Each test gets its own context. No global state. No race conditions. No mocking frameworks.
See the Testing Guide for comprehensive patterns.
This project is licensed under the MIT License - see the LICENSE file for details.