Dependency Injection
Bu içerik henüz dilinizde mevcut değil.
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:
1const client = new Client({2 ...options,3});4
5Sern.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.
1interface MyDependencies extends Dependencies {2 "@sern/client": Singleton<Client>;3}
Full Example
Your full setup may have the following structure:
Dizinsrc/
- index.ts (your main file and client)
- dependencies.d.ts (for intellisense)
1const client = new Client({2 ...options,3});4
5interface MyDependencies extends Dependencies {6 "@sern/client": Singleton<Client>;7}8
9export 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.
1export const useContainer = Sern.makeDependencies<MyDependencies>({2 build: (root) =>3 root4 .add({5 "@sern/client": single(() => client),6 })7 .addDisposer({ "@sern/client": (client) => client.destroy() }),8});
Init
-
Do you need to perform intializing behavor for a dependency?
src/database.ts 1import { Init } from "@sern/handler";23class Database implements Init {4init() {5await this.connect();6console.log("Connected");7}8} -
Modify your
Dependencies
interface:src/dependencies.d.ts 1import type { Initializable } from "@sern/handler";23interface Dependencies extends CoreDependencies {4database: Initializable<Database>;5} -
Make sure its been added:
src/index.ts 1await makeDependencies({2build: root => root3.add({ database => new Database() })4}) -
Now, when your bot starts, the
init
method will be called. 🎉