项目作者: Abdulrahman-Tayara

项目描述 :
Typescript Dependency Injection Library
高级语言: TypeScript
项目地址: git://github.com/Abdulrahman-Tayara/get-it-di.git
创建时间: 2021-07-18T19:49:29Z
项目社区:https://github.com/Abdulrahman-Tayara/get-it-di

开源协议:

下载


npm

get-it-di

Typescript Dependency Injection Library

Installation

Install by npm:

  1. npm install get-it-di

Install by yarn:

  1. yarn add get-it-di

Api:

Create Container:

  1. import {ContainerFactory} from "get-it-di";
  2. const container = ContainerFactory.create();

register:

  1. class Car {
  2. constructor(public name: string) {
  3. }
  4. }
  5. container.register<Car>(Car, () => new Car("Car1"))
  6. // or you can register by Key
  7. container.register<Car>("CAR_KEY", () => new Car("Car2"))
  8. const resolvedCar = container.resolve(Car)
  9. console.log(resolvedCar.name)
  10. // output: Car1
  11. const resolvedCarByKey = container.resolve<Car>("CAR_KEY")
  12. console.log(resolvedCarByKey.name)
  13. // output: Car2

By using this method, you’ll get a new instance of the class in each resolving call

registerSingleton:

  1. class Car {
  2. constructor(public name: string) {
  3. }
  4. }
  5. container.registerSingleton<Car>(Car, new Car("1"))
  6. const resolvedCar = container.resolve(Car)
  7. console.log(resolvedCar.name)
  8. // output: Car1

By using this method, you’ll get the same instance of the class in each resolving call.
This method requires a direct object/value.

registerLazySingleton:

  1. class Car {
  2. constructor(public name: string) {
  3. }
  4. }
  5. container.registerLazySingleton<Car>(Car, () => new Car("1"))
  6. const resolvedCar = container.resolve(Car)
  7. console.log(resolvedCar.name)
  8. // output: Car1

By using this method, you’ll get the same instance of the class in each resolving call.

Interfaces:

  1. class ApiClient {
  2. }
  3. interface IUserRepository {
  4. get(id: string): User;
  5. }
  6. class UserRepository implements IUserRepository {
  7. constructor(private api: ApiClient) {
  8. }
  9. get(id: string): User {
  10. }
  11. }
  12. // Register
  13. container.registerLazySingleton<ApiClient>(ApiClient, () => new ApiClient())
  14. container.registerLazySingleton<IUserRepository>(
  15. "USER_REPOSITORY",
  16. (c) => {
  17. return new UserRepository(c.resolve<ApiClient>(ApiClient))
  18. }
  19. )
  20. // Resolve
  21. const userRepository = container.resolve<IUserRepository>("USER_REPOSITORY")