Migration Guide: Container Pattern & Dependency Injection
This guide helps you migrate your code to use the new container pattern and dependency injection.Overview
We’ve introduced a dependency injection container pattern to replace global singletons, making the codebase more testable and flexible. Benefits:- ✅ Easier testing (no global state!)
- ✅ Multiple independent agent instances
- ✅ Per-tenant/per-agent configuration
- ✅ No environment variable pre-seeding in tests
- ✅ Better type safety and IDE support
What Changed?
Phase 1: Test Infrastructure (✅ Complete)
Before:- Use
test_containerfixture instead of manual setup - Remove environment variable pre-seeding from tests
- Use
create_test_agent()helper for agent instances
Phase 2: Agent Creation (✅ Complete)
Before:- Replace
get_agent_graph()withcreate_agent() - Pass
containerparameter for full DI benefits - Update tests to use
create_test_agent()helper
Backward Compatibility
The oldget_agent_graph() function still works:
- ✅ Now: New code uses
create_agent() - v2.0:
get_agent_graph()marked as deprecated in docstring - v3.0:
get_agent_graph()removed
Testing Migration
Old Pattern (❌ Don’t use)
New Pattern (✅ Use this)
Common Migration Patterns
Pattern 1: Test Setup
Before:Pattern 2: Custom Configuration
Before:Pattern 3: Multiple Agents
Before:Helper Functions Reference
Container Helpers
Agent Helpers
Test Helpers
Troubleshooting
Issue: Tests fail with “observability not initialized”
Cause: Old code trying to use global initialization Solution:Issue: Multiple tests share state
Cause: Using singletonget_agent_graph()
Solution:
Issue: Can’t override settings in tests
Cause: Global settings being used Solution:Best Practices
✅ Do
-
Use containers in new code
-
Use test helpers
-
Create isolated instances
-
Use fixtures
❌ Don’t
-
Don’t modify global state
-
Don’t use singletons in new code
-
Don’t pre-seed environment variables
Timeline & Rollout
Phase 1 (✅ Complete)
- Container implementation
- Test infrastructure migration
- Helper functions
Phase 2 (✅ Complete)
- Agent factory functions
- Test helper updates
- Documentation
Phase 3 (🚧 Future)
- Server refactoring
- Infrastructure layer extraction
- Complete singleton removal
Questions?
- See
/docs/day-1-developer.mdfor quickstart guide - See
/tests/core/test_container.pyfor examples - See
/tests/core/test_agent_di.pyfor agent examples