Skip to content

Very simple implementation of Dependency Injection based on latest version of javascript decorators

Notifications You must be signed in to change notification settings

DevMoroh/simple-injector

Repository files navigation

Decorator-injector

Decorator-injector is a very lightweight Dependency Injection ts library
Features:

  • is very small and simple usage
  • built on TypeScript 5.*
  • latest decorator proposal (stage-3) https://github.com/tc39/proposal-decorators
  • class fields can be decorated
  • no need to use reflect-metadata or other extra packages

Examples of usage:

Register class as DI with decorator:

@Injectable("AnotherService")
export class AnotherService {
    helloWorld() {
        console.log("Hello world! Injected AnotherService");
    }
}

Inject as class field

export class AnotherServiceTwo {
    @Inject("AnotherService") anotherService: AnotherService;

    async run() {
        this.anotherService.helloWorld();
    }
}

Register dependency directly (free to customize)

register("Knex", {
    create(args: any[]) {
        // some logic you might need
        return new MyClass(args)
    }
})

Register Knex dependency

register("Knex", {
    create(options: { connection?: any }) {
        if (!options.connection) {
            throw new Error("Database connection config is not defined");
        }
        return knex({
            client: "pg",
            connection: options.connection,
        });
    },
});

export class AnotherServiceTwo {
    @Inject("Knex", {
        connection: {
            user: "user",
            database: "admin",
            password: "1234****",
            host: "hattie.db.com",
            ssl: true,
        },
    })
    knex: Knex;

    async run() {
        const result = await this.knex.raw("SELECT 1");
    }
}

const anotherService = new AnotherServiceTwo();

await anotherService.run();

About

Very simple implementation of Dependency Injection based on latest version of javascript decorators

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published