honojs-middleware/packages/tsyringe
Jonathan Haines b18f24379b
chore(dev-deps): upgrade to hono v4 (#1092)
* chore(dev-deps): upgrade to hono v4

* chore(zod-openapi): build workspace dependencies

* chore(trpc-server): ignore null body type
2025-03-31 18:20:57 +09:00
..
src test: move tests to src directory (#1075) 2025-03-28 18:50:19 +09:00
CHANGELOG.md Version Packages (#835) 2024-11-18 11:14:07 +09:00
README.md chore: add coverage badges (#1023) 2025-03-19 17:53:11 +09:00
package.json chore(dev-deps): upgrade to hono v4 (#1092) 2025-03-31 18:20:57 +09:00
tsconfig.json build(tsyringe): lint published package (#1065) 2025-03-27 13:13:54 +09:00
vitest.config.ts test(workspace): upgrade to vitest v3 (#1009) 2025-03-12 12:52:15 +09:00

README.md

tsyringe middleware for Hono

codecov

The tsyringe middleware provides a way to use dependency injection in Hono.

Usage

import 'reflect-metadata' // tsyringe requires reflect-metadata or polyfill
import { container, inject, injectable } from 'tsyringe'
import { tsyringe } from '@hono/tsyringe'
import { Hono } from 'hono'

@injectable()
class Hello {
  constructor(@inject('name') private name: string) {}

  greet() {
    return `Hello, ${this.name}!`
  }
}

const app = new Hono()

app.use(
  '*',
  tsyringe((container) => {
    container.register('name', { useValue: 'world' })
  })
)

app.get('/', (c) => {
  const hello = container.resolve(Hello)
  return c.text(hello.greet())
})

export default app

With providers

const app = new Hono()

app.use('/tenant/:name/*', async (c, next) => {
  await tsyringe((container) => {
    // Allowing to inject `c.var` or `c.req.param` in the providers
    const tenantName = c.req.param('name')

    container.register(Config, { useFactory: () => new Config(tenantName) })
  })(c, next)
})

Author

Aotokitsuruya https://github.com/elct9620

License

MIT