Using DI Container.md - Mirroar/hivemind GitHub Wiki
Using the DI Container
Hivemind uses a simple Dependency Injection (DI) container to manage its core services and managers. This allows you to swap out or extend internal components without modifying the bot's core code, making your changes more maintainable and upgrade-friendly.
How the Container Works
- The DI container holds references to many major services (e.g., managers, reports, utility classes).
- Each service is registered with a unique key (like
'RoomStatus'
,'NavMesh'
, etc.), usually using the class name. - When the bot needs a service, it asks the container for it. The container will create the service if it doesn't exist yet, or return the existing instance.
Swapping Implementations
You can replace any service with your own implementation by calling container.set
with the appropriate key and a factory function. The best place to do this is in your onGlobalReset
callback, so your changes are applied every time the bot reloads.
Example: Replacing the RoomStatus Service
Create your own implementation in src/my-room-status.ts
:
import RoomStatus from './room/room-status';
export default class MyRoomStatus extends RoomStatus {
// Override or extend methods here
}
Then, in your src/my-custom-callbacks.ts
:
import container from 'utils/container';
import MyRoomStatus from './my-room-status';
export function myOnGlobalReset() {
container.set('RoomStatus', () => new MyRoomStatus());
}
And reference this callback in your settings.local.ts
:
import {myOnGlobalReset} from './my-custom-callbacks';
const settings: Partial<SettingsObject> = {
onGlobalReset: myOnGlobalReset,
};
export default settings;
Best Practices
- Always use
onGlobalReset
to register your custom services, so they are set up after every global reset. - Only override the services you need to change; the rest will use the default implementations.
- You can find the list of available service keys in
src/container-factory.ts
.
You can now extend or replace any major part of the bot's architecture in a clean, upgrade-safe way! If you need to be able to modify a service that is not registered in the DI container, feel free to open an issue or PR to add it.