Skip to content
sern

Dependency Injection

Since version 2.0.0, dependency injection, thanks to iti, is a feature to customize your bot’s utilities and structures.

For example, a minimal setup for any project might look like this:

src/index.ts
1
const client = new Client({
2
...options,
3
});
4
5
Sern.makeDependencies<MyDependencies>({
6
build: (root) =>
7
root.add({
8
"@sern/client": single(() => client),
9
}),
10
});

For any TypeScript project, you’ll need to add an interface to get intellisense and typings.

src/dependencies.d.ts
1
interface MyDependencies extends Dependencies {
2
"@sern/client": Singleton<Client>;
3
}

Full Example

Your full setup may have the following structure:

  • Directorysrc/
    • index.ts (your main file and client)
    • dependencies.d.ts (for intellisense)
src/index.ts
1
const client = new Client({
2
...options,
3
});
4
5
interface MyDependencies extends Dependencies {
6
"@sern/client": Singleton<Client>;
7
}
8
9
export const useContainer = Sern.makeDependencies<MyDependencies>({
10
build: (root) =>
11
root.add({
12
"@sern/client": single(() => client),
13
}),
14
});

Everything else is handled. However, you may want customize things.

Adding Dependencies to Root

Each sern built dependency must implement its contracts:

  • @sern/logger: Logging data → Logging
  • @sern/errors: Handling errors and lifetime → ErrorHandling
  • @sern/modules: Managing all command modules → ModuleManager
  • @sern/emitter: The key to emit events and occurences in a project → Emitter

You may also add disposers so that when the application crashes, the targeted dependency calls that function.

src/index.ts
1
export const useContainer = Sern.makeDependencies<MyDependencies>({
2
build: (root) =>
3
root
4
.add({
5
"@sern/client": single(() => client),
6
})
7
.addDisposer({ "@sern/client": (client) => client.destroy() }),
8
});

Init

  1. Do you need to perform intializing behavor for a dependency?

    src/database.ts
    1
    import { Init } from "@sern/handler";
    2
    3
    class Database implements Init {
    4
    init() {
    5
    await this.connect();
    6
    console.log("Connected");
    7
    }
    8
    }
  2. Modify your Dependencies interface:

    src/dependencies.d.ts
    1
    import type { Initializable } from "@sern/handler";
    2
    3
    interface Dependencies extends CoreDependencies {
    4
    database: Initializable<Database>;
    5
    }
  3. Make sure its been added:

    src/index.ts
    1
    await makeDependencies({
    2
    build: root => root
    3
    .add({ database => new Database() })
    4
    })
  4. Now, when your bot starts, the init method will be called. 🎉