Bind Provider service in application.ts

12 views
Skip to first unread message

Mohit Aggarwal

unread,
May 29, 2021, 11:57:45 PM5/29/21
to LoopbackJS
Hi team,

I have created a provider service and want to bind it to context/application.

When I am trying to bind using 

this.bind(`${key}`).toProvider(<ProviderClass>)
It doesn't give error but my provider function does not run.

Can you please help?

Thanks and regards,
Mohit Aggarwal

rifa...@gmail.com

unread,
May 30, 2021, 3:58:09 AM5/30/21
to LoopbackJS
Hi Aggarwal,

A Provider or Class that's bound to context isn't instantiated until it is resolved (either by `@inject()`, `app.get()`, or through other means). Hence, it's possible to instantiate the Provider by calling "await this.get(`${key}`)".

Though do note that, by default, Bindings are always bound in the Transient scope; This means that, every time the Class or Provider Binding is resolved, a new instance will be created.

If only a single instance is desired, the code can be modified as follows:

```
import {BindingType} from '@loopback/core';
// ...
this.bind(`${key}`).toProvider(<ProviderClass>).inScope(BindingType.SINGLETON);
```

Though also do note that Singletons mean that any `@inject()` (or other similar DI decorators) will only be resolved once. A way around this is to use Getters (i.e. `@inject.getter()`), which allows dynamic dependency resolution.
Reply all
Reply to author
Forward
0 new messages