Skip to content

How to use tsyringe with own decorators #233

@Amirust

Description

@Amirust

Hi, for example we have code

// IConfig.ts
interface IConfig {
    get<T>(key: string): string | null
}

// ConfigService.ts
class ConfigService implements IConfig {
    public get<T>(key: string) { .... }
}

// container.ts
...
container.register("Config", { useClass: useClass })
...

// ServiceDecorator.ts
export function ServiceDecorator<T extends { new (...args: any[]): {} }>(name: string) {
    return function (target: T) {
        return class extends target {
            public readonly name: string = name;
        };
    };
}

// SmthService.ts
@ServiceDecorator("nameOfService")
@injectable()
class SmthService {
    public name: string;
    constructor(@inject("Config") private config: IConfig) {}

    someMethod() { console.log(this.name) }
}

// index.ts

const smthService = container.resolve(SmthService)
smthService.someMethod() // undefined

It will not insert name to object because ServiceDecorator create own instance and injectable create own, how i can fix it?
(pls dont "just write public name: string = nameOfService;")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions