Files
website/docs/guide/walkthrough/dependency-injection.md
2023-06-28 10:34:30 -05:00

1.9 KiB

sidebar_position
sidebar_position
7

:::warning This is version 2 code. Please view transitioning to v3 ::: Since version 2.0.0, dependency injection, thanks to iti, is a feature to customize your bot's utilities and structures.

Minimal setup for any project.

const client = new Client({
    ...options
})
Sern.makeDependencies<MyDependencies>({
    build: root => 
        root.add({ 
            '@sern/client': single(() => client)
        })
})

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

interface MyDependencies extends Dependencies {
    '@sern/client': Singleton<Client>
}

Full Dependency Injection setup

const client = new Client({
    ...options
})

interface MyDependencies extends Dependencies {
    '@sern/client': Singleton<Client>
}

export const useContainer = Sern.makeDependencies<MyDependencies>({
    build: root => 
        root.add({ 
            '@sern/client': single(() => client)
        })
})

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

Adding dependencies to root

Each sern built dependency must implement its contracts.

  • @sern/logger: Log data. Logging
  • @sern/errors: Handling errors and lifetime. ErrorHandling
  • @sern/modules: Managing all command modules. ModuleManager
  • @sern/emitter: is the key to emit events and occurences in a project. SernEmitter

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

export const useContainer = Sern.makeDependencies<MyDependencies>({
   build: root => 
       root.add({ 
           '@sern/client': single(() => client)
       })
       .addDisposer({ '@sern/client': client => client.destroy() })
})