microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.16k stars 173 forks source link

How to use tsyringe with own decorators #233

Closed Amirust closed 11 months ago

Amirust commented 11 months ago

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;")

Amirust commented 11 months ago

I found a fix here https://github.com/microsoft/tsyringe/issues/54#issuecomment-530924841