container.ts
This file provides a system called a "Dependency Injection (DI) Container",
created using createContainer()
. Its main job is to manage shared resources or
services that different parts of your agent might need, like a connection to an
external API, a database client, or the agent's logger. It ensures these
resources are created correctly and makes them easily accessible wherever
needed.
How to Use
You generally don't create or directly interact with the container yourself
using createContainer()
. The Daydreams framework creates one automatically
when you call createDreams
.
- Registering: Services (defined using the
service
helper) or Extensions use the container'sregister
,singleton
, orinstance
methods internally to tell the container how to create or find a specific resource (e.g., "Here's how to make the database client").singleton
is common for resources you only want one of (like a database connection). - Accessing: When your
action
handler (or other component) needs to use a shared resource managed by the container, you access it through theagent
object:agent.container.resolve<ResourceType>('resourceName')
. For example, to get the logger, you might useagent.container.resolve<Logger>('logger')
.
Benefit
The container decouples your code. Your action handler doesn't need to know
how to create the database client or logger; it just asks the container for it
by name ('database'
, 'logger'
). This makes your code cleaner, easier to
test, and simplifies managing shared resources, especially within extensions. If
the way a resource is created changes, you only need to update its registration,
not every place it's used.
Anticipated Questions
- "Do I need to call
createContainer()
?" No, the agent created bycreateDreams
already includes a pre-configured container available atagent.container
. - "How do things get into the container?" Typically through
ServiceProvider
definitions (created with theservice
helper), which are often bundled withinExtension
s. The service'sregister
method puts things into the container. Core framework components like the defaultLogger
are also registered automatically. - "What's the difference between
register
andsingleton
?" When registering,singleton
ensures only one instance of the resource is ever created and shared.register
creates a new instance every timeresolve
is called for that name (less common for shared resources).