Daydreams Logo
Extra reading

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's register, singleton, or instance 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 the agent object: agent.container.resolve<ResourceType>('resourceName'). For example, to get the logger, you might use agent.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 by createDreams already includes a pre-configured container available at agent.container.
  • "How do things get into the container?" Typically through ServiceProvider definitions (created with the service helper), which are often bundled within Extensions. The service's register method puts things into the container. Core framework components like the default Logger are also registered automatically.
  • "What's the difference between register and singleton?" When registering, singleton ensures only one instance of the resource is ever created and shared. register creates a new instance every time resolve is called for that name (less common for shared resources).

On this page