typedi icon indicating copy to clipboard operation
typedi copied to clipboard

question: Inject Private Property

Open bestickley opened this issue 3 years ago • 2 comments

I was trying to... inject a private property: image

The problem: I'm getting the TypeScript error: "Decorators are not valid here"

bestickley avatar Jul 21 '22 17:07 bestickley

That is expected, private fields cannot be decorated by design. However, you can try to create a getter and decorate that. (I haven’t tried it myself, but the spec allows it)

attilaorosz avatar Jul 21 '22 17:07 attilaorosz

@attilaorosz - this is not true. It used to work in earlier versions. Started to acting up around 0.8.0. Currently with 0.10.0 I find, that @Inject() works in one place in code and fails in others. Calling container directly via Container.get in the same place works with no issue.

This used to work but doesn't anymore with 0.10.0:

@Service()
@RestController('some-settings', 2)
export class SomeSettingsV2Resource {
    @Inject()
     private getAlHandler: GetAllHandler;

    @Inject()
    private getSomeSettingsHandler: GetSomeSettingsHandler;

}

this also doesn't work:

@Service()
@RestController('some-settings', 2)
export class SomeSettingsV2Resource {
    constructor(
        @Inject(() => GetAllHandler)
        private readonly getAllHandler: GetAllHandler,
        @Inject(() => GetSettingHandler)
        private readonly getSettingHandler: GetSettingHandler
    ) {} 
}

This works though:

@Service()
@RestController('some-settings', 2)
export class SomeSettingsV2Resource {
   
    constructor(
        private readonly getAllHandler: GetAllHandler = Container.get(GetAllHandler),
        private readonly getSettingHandler: GetSettingHandler = Container.get(GetSettingHandler)
    ) {}
       
}

wladzynski avatar Sep 28 '23 10:09 wladzynski