flex-injector

0.0.3 • Public • Published

Flex-Injector

npm version

English | 한국어

Flex-Injector is a library that makes dependency injection easy. This library utilizes TypeScript's decorator feature to manage dependencies in a simple and clear way.

Using createInjector, you can create multiple injectors and inject dependencies through different containers. This is particularly useful in a monorepo environment. Each package or module can use an independent injector, making dependency management more efficient and clear.

Installation

  1. Install module:
npm install flex-injector
  1. Install peer dependencies:
npm install reflect-metadata
  1. tsconfig.json compilerOptions :
{
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true
}

Example of usage

./service
├── todo.service.ts
├── user.service.ts
└── injector.ts
//  ./service/injector.ts

import { createInjector } from 'flex-injector';

const { InjectAble, inject } = createInjector();

export { InjectAble, inject };
//  ./service/todo.service.ts

import { InjectAble } from './injector';

@InjectAble
export class TodoService {

  async getTodo(userId:string) {
    return ...;
  }
}
//  ./service/user.service.ts

import { InjectAble } from './injector';

@InjectAble
export class UserService {

  constructor(private todoService: TodoService) {}


  async getTodo(userId:string) {
    return this.todoService.getTodo(userId);
  }

  async find(userId:string) {
    return ...;
  }
}
// express server example

const userService = inject(UserService);

app.get('/todo', async (req, res) => {
  const todoList = await userService.getTodo(req.session.userId);
  res.json(todoList);
});

❌ Bad Case

//  Beware of circular reference errors. Below is a bad example where circular references occur.

import { InjectAble, inject } from './injector';

@InjectAble
class A {
  constructor(private b: B) {}
}

@InjectAble
class B {
  constructor(private a: A) {}
}

const injector = createInjector();
const a = inject(A); // Throw Circular dependency detected

More examples

Package Sidebar

Install

npm i flex-injector

Weekly Downloads

2

Version

0.0.3

License

MIT

Unpacked Size

13.5 kB

Total Files

15

Last publish

Collaborators

  • cgoing