Basic Example
This example demonstrates the core functionality of the gioc package.
What it demonstrates
- Registering constructors with
gioc.Register()
- Automatic constructor injection (parameters resolved from the container)
- Singleton behavior – constructors are called only once
- Startup validation with
gioc.Validate()
- Retrieving instances with
gioc.Get[T]()
Code explanation
The example creates a three-layer dependency chain using the global default container:
UserRepository – data access layer (no dependencies)
UserService – depends on *UserRepository
UserHandler – depends on *UserService
All constructors are registered up front. Validate() checks for missing dependencies and cycles at startup. When Get[*UserHandler]() is called, the container resolves the full dependency chain automatically, creating each component exactly once.
Output
NewUserRepository called
NewUserService called
NewUserHandler called
handler1 == handler2: true (singleton)
Each constructor runs once. Both handler1 and handler2 point to the same instance.