Nest: When to use @Inject()?

Created on 22 Mar 2019  路  9Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

When creating services, I simply inject them to a controller as follows:

constructor(private myService: MyService) {}

While reading the section of custom providers it mentions that I should use @Inject() when I want to inject a provider.

I am confused. When to use @Inject() and when it is not needed?
Thanks

Most helpful comment

Basically if the type of what you want to inject is a class then you can avoid to use @Inject, otherwise use it :)

All 9 comments

You can use @Inject when you create a custom provider with a custom token which is not a class that can be interpreted as a type and instanciate. for example when you use a factory if you provide a string based token you can inject it with this decorator.

@adrien2p So it's only used when using a string-based token? Other than that, no need to use it when injecting providers?

No, it could be a Symbol as well.

But if the injection you want to achieve is base on a class, you don鈥檛 need it.

What do you mean by Symbol?

Oh great! Symbol reminds of InjectionToken.

Thanks @adrien2p a lot! I am paving my way through nestjs still.

Basically if the type of what you want to inject is a class then you can avoid to use @Inject, otherwise use it :)

I believe that this issue can be closed then :)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

marshall007 picture marshall007  路  3Comments

rafal-rudnicki picture rafal-rudnicki  路  3Comments

FranciZ picture FranciZ  路  3Comments

2233322 picture 2233322  路  3Comments

rlesniak picture rlesniak  路  3Comments