2024-11-17 04:36:39 +08:00
|
|
|
# tsyringe middleware for Hono
|
|
|
|
|
2025-03-19 16:53:11 +08:00
|
|
|
[](https://codecov.io/github/honojs/middleware)
|
|
|
|
|
2024-11-17 04:36:39 +08:00
|
|
|
The [tsyringe](https://github.com/microsoft/tsyringe) middleware provides a way to use dependency injection in [Hono](https://hono.dev/).
|
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
|
|
```ts
|
2025-03-19 16:53:11 +08:00
|
|
|
import 'reflect-metadata' // tsyringe requires reflect-metadata or polyfill
|
2024-11-17 04:36:39 +08:00
|
|
|
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()
|
|
|
|
|
2025-03-19 16:53:11 +08:00
|
|
|
app.use(
|
|
|
|
'*',
|
|
|
|
tsyringe((container) => {
|
2024-11-17 04:36:39 +08:00
|
|
|
container.register('name', { useValue: 'world' })
|
2025-03-19 16:53:11 +08:00
|
|
|
})
|
|
|
|
)
|
2024-11-17 04:36:39 +08:00
|
|
|
|
|
|
|
app.get('/', (c) => {
|
2025-03-19 16:53:11 +08:00
|
|
|
const hello = container.resolve(Hello)
|
|
|
|
return c.text(hello.greet())
|
2024-11-17 04:36:39 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
export default app
|
|
|
|
```
|
|
|
|
|
|
|
|
### With providers
|
|
|
|
|
|
|
|
```ts
|
|
|
|
const app = new Hono()
|
|
|
|
|
|
|
|
app.use('/tenant/:name/*', async (c, next) => {
|
2025-03-19 16:53:11 +08:00
|
|
|
await tsyringe((container) => {
|
|
|
|
// Allowing to inject `c.var` or `c.req.param` in the providers
|
|
|
|
const tenantName = c.req.param('name')
|
2024-11-17 04:36:39 +08:00
|
|
|
|
2025-03-19 16:53:11 +08:00
|
|
|
container.register(Config, { useFactory: () => new Config(tenantName) })
|
|
|
|
})(c, next)
|
2024-11-17 04:36:39 +08:00
|
|
|
})
|
|
|
|
```
|
|
|
|
|
|
|
|
## Author
|
|
|
|
|
|
|
|
Aotokitsuruya <https://github.com/elct9620>
|
|
|
|
|
|
|
|
## License
|
|
|
|
|
|
|
|
MIT
|