async-injection 2.2.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ReadMe.md +134 -194
- package/lib/async-factory-provider.d.ts +4 -4
- package/lib/bindable-provider.d.ts +4 -4
- package/lib/binding.d.ts +80 -0
- package/lib/cjs/async-factory-provider.js +5 -5
- package/lib/cjs/async-factory-provider.js.map +1 -1
- package/lib/cjs/bindable-provider.js +23 -36
- package/lib/cjs/bindable-provider.js.map +1 -1
- package/lib/cjs/{binder.js → binding.js} +1 -1
- package/lib/cjs/binding.js.map +1 -0
- package/lib/cjs/class-provider.js +168 -66
- package/lib/cjs/class-provider.js.map +1 -1
- package/lib/cjs/constant-provider.js +4 -4
- package/lib/cjs/constant-provider.js.map +1 -1
- package/lib/cjs/container.js +81 -45
- package/lib/cjs/container.js.map +1 -1
- package/lib/cjs/decorators.js +80 -40
- package/lib/cjs/decorators.js.map +1 -1
- package/lib/cjs/index.js +10 -10
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/injector.js +5 -5
- package/lib/cjs/injector.js.map +1 -1
- package/lib/cjs/provider.js +16 -11
- package/lib/cjs/provider.js.map +1 -1
- package/lib/cjs/state.js +2 -2
- package/lib/cjs/state.js.map +1 -1
- package/lib/cjs/sync-factory-provider.js +7 -7
- package/lib/cjs/sync-factory-provider.js.map +1 -1
- package/lib/cjs/utils.js +10 -13
- package/lib/cjs/utils.js.map +1 -1
- package/lib/class-provider.d.ts +20 -6
- package/lib/constant-provider.d.ts +2 -2
- package/lib/container.d.ts +45 -19
- package/lib/decorators.d.ts +16 -3
- package/lib/esm/async-factory-provider.js +1 -1
- package/lib/esm/async-factory-provider.js.map +1 -1
- package/lib/esm/bindable-provider.js +19 -32
- package/lib/esm/bindable-provider.js.map +1 -1
- package/lib/esm/binding.js +2 -0
- package/lib/esm/binding.js.map +1 -0
- package/lib/esm/class-provider.js +155 -53
- package/lib/esm/class-provider.js.map +1 -1
- package/lib/esm/constant-provider.js.map +1 -1
- package/lib/esm/container.js +63 -27
- package/lib/esm/container.js.map +1 -1
- package/lib/esm/decorators.js +61 -22
- package/lib/esm/decorators.js.map +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/injector.js +5 -5
- package/lib/esm/injector.js.map +1 -1
- package/lib/esm/provider.js +14 -9
- package/lib/esm/provider.js.map +1 -1
- package/lib/esm/state.js.map +1 -1
- package/lib/esm/sync-factory-provider.js +1 -1
- package/lib/esm/sync-factory-provider.js.map +1 -1
- package/lib/esm/utils.js +6 -8
- package/lib/esm/utils.js.map +1 -1
- package/lib/index.d.ts +4 -3
- package/lib/injector.d.ts +1 -1
- package/lib/provider.d.ts +4 -4
- package/lib/state.d.ts +3 -3
- package/lib/sync-factory-provider.d.ts +5 -5
- package/package.json +7 -18
- package/lib/binder.d.ts +0 -106
- package/lib/cjs/binder.js.map +0 -1
- package/lib/esm/binder.js +0 -2
- package/lib/esm/binder.js.map +0 -1
package/ReadMe.md
CHANGED
|
@@ -1,42 +1,26 @@
|
|
|
1
1
|
# Async-Injection
|
|
2
|
-
|
|
3
|
-
[](https://github.com/pcafstockf/async-injection/actions)
|
|
4
|
+
[](https://www.npmjs.com/package/async-injection)
|
|
5
|
+
[](https://codecov.io/gh/pcafstockf/async-injection)
|
|
4
6
|
[](https://opensource.org/licenses/MIT)
|
|
5
7
|

|
|
6
|
-
[](https://www.npmjs.com/package/async-injection)
|
|
7
|
-
|
|
8
|
-
A robust lightweight dependency injection library for TypeScript.
|
|
9
|
-
|
|
10
|
-
## About
|
|
11
|
-
Async-Injection is a small IoC container with support for both synchronous and asynchronous dependency injection, as well as isolated and/or hierarchical scopes.
|
|
12
|
-
|
|
13
|
-
## Installation
|
|
14
|
-
|
|
15
|
-
You can get the latest release from [npm](https://www.npmjs.com/package/async-injection):
|
|
16
8
|
|
|
17
|
-
|
|
18
|
-
$ npm install async-injection --save
|
|
19
|
-
```
|
|
9
|
+
**Lightweight TypeScript dependency injection — with first-class async support.**
|
|
20
10
|
|
|
21
|
-
|
|
22
|
-
|
|
11
|
+
Most DI containers assume your dependencies are ready the moment they are constructed. `async-injection` doesn't.
|
|
12
|
+
Synchronous and asynchronous dependencies can coexist naturally in the same container, and the library resolves each correctly — whether you get them immediately or need to await them.
|
|
23
13
|
|
|
24
|
-
|
|
25
|
-
- [core-js (core-js/es7/reflect)](https://www.npmjs.com/package/core-js)
|
|
26
|
-
- [reflection](https://www.npmjs.com/package/@abraham/reflection)
|
|
14
|
+
## Install
|
|
27
15
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
```typescript
|
|
31
|
-
// entry.ts
|
|
32
|
-
import "reflect-metadata";
|
|
33
|
-
// Your code here...
|
|
16
|
+
```bash
|
|
17
|
+
npm install async-injection
|
|
34
18
|
```
|
|
35
19
|
|
|
36
|
-
|
|
20
|
+
Works in Node, browsers, Electron, and other runtimes.
|
|
21
|
+
Ships as both ESM and CJS side by side.
|
|
37
22
|
|
|
38
|
-
##
|
|
39
|
-
Here we 'get' a new transaction handling object, that itself, relies on a shared service:
|
|
23
|
+
## Quick start
|
|
40
24
|
|
|
41
25
|
```typescript
|
|
42
26
|
@Injectable()
|
|
@@ -49,209 +33,165 @@ class TransactionHandler {
|
|
|
49
33
|
constructor(svc: SharedService) { }
|
|
50
34
|
}
|
|
51
35
|
|
|
52
|
-
// Create a simple container (we will bind providers into it).
|
|
53
36
|
const container = new Container();
|
|
37
|
+
container.bindClass(SharedService).asSingleton(); // one shared instance
|
|
38
|
+
container.bindClass(TransactionHandler); // new instance on each get
|
|
39
|
+
container.bindConstant('LogLevel', 'info'); // override defaulted 'warn' level
|
|
54
40
|
|
|
55
|
-
// A single instance will be created and shared by everyone.
|
|
56
|
-
container.bindClass(SharedService).asSingleton();
|
|
57
|
-
|
|
58
|
-
// A new instance will be created each time one is requested.
|
|
59
|
-
container.bindClass(TransactionHandler);
|
|
60
|
-
|
|
61
|
-
// If we omit this line, the logLevel of SharedService will be initialized to 'warn'
|
|
62
|
-
container.bindConstant('LogLevel', 'info');
|
|
63
|
-
|
|
64
|
-
// In our request processing code (which would be an anti-pattern)...
|
|
65
|
-
// Instantiate a new transaction handler (it will be injected with the shared service).
|
|
66
41
|
const tx = container.get(TransactionHandler);
|
|
67
42
|
```
|
|
68
|
-
**NOTE:**
|
|
69
|
-
The examples in this ReadMe are contrived to quickly communicate concepts and usage.
|
|
70
|
-
Your real world project should of course follow best practices like [separation of concerns](https://medium.com/machine-words/separation-of-concerns-1d735b703a60), having a [composition root](https://medium.com/@cfryerdev/dependency-injection-composition-root-418a1bb19130), and should avoid anti-patterns like [service locator](http://scotthannen.org/blog/2018/11/27/stop-worrying-love-service-locator.html).
|
|
71
43
|
|
|
72
|
-
|
|
73
|
-
|
|
44
|
+
> **Tip:**
|
|
45
|
+
> Real-world projects should follow best practices like [separation of concerns](https://medium.com/machine-words/separation-of-concerns-1d735b703a60), having a [composition root](https://medium.com/@cfryerdev/dependency-injection-composition-root-418a1bb19130), and should avoid anti-patterns like [service locator](http://scotthannen.org/blog/2018/11/27/stop-worrying-love-service-locator.html).
|
|
74
46
|
|
|
75
|
-
##
|
|
76
|
-
Why reinvent the wheel? TypeScript is great!
|
|
77
|
-
Implement the "module" you want and just import it:
|
|
47
|
+
## Setup
|
|
78
48
|
|
|
79
|
-
`
|
|
80
|
-
```typescript
|
|
81
|
-
import {myContainer} from './app';
|
|
82
|
-
import {Logger, HttpClient} from './services';
|
|
83
|
-
import {HttpClientGotWrapper} from './impl';
|
|
49
|
+
Two `tsconfig.json` settings are required:
|
|
84
50
|
|
|
85
|
-
|
|
86
|
-
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"experimentalDecorators": true,
|
|
54
|
+
"emitDecoratorMetadata": true
|
|
55
|
+
}
|
|
87
56
|
```
|
|
88
57
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
58
|
+
Reflection metadata is also required. Rather than mandate a specific library, you have the freedom to bring your own — choose whichever fits your project:
|
|
59
|
+
* [reflect-metadata](https://www.npmjs.com/package/reflect-metadata)
|
|
60
|
+
* [core-js/es7/reflect](https://www.npmjs.com/package/core-js)
|
|
61
|
+
* [@abraham/reflection](https://www.npmjs.com/package/@abraham/reflection)
|
|
93
62
|
|
|
94
|
-
|
|
95
|
-
Perhaps in the example above, our `SharedService` is useless until it has established a database connection.
|
|
96
|
-
Of course such a simple scenario could easily be handled in user-land code, but as application complexity grows, this becomes more tedious and difficult to maintain.
|
|
97
|
-
Let's modify the example as follows:
|
|
63
|
+
Import it once at your entry point, before anything else:
|
|
98
64
|
```typescript
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
constructor() { }
|
|
102
|
-
connect(): Promise<void> { ... }
|
|
103
|
-
}
|
|
65
|
+
import 'reflect-metadata';
|
|
66
|
+
```
|
|
104
67
|
|
|
105
|
-
|
|
68
|
+
## Async dependencies
|
|
69
|
+
|
|
70
|
+
Synchronous injection is straightforward and well understood.
|
|
71
|
+
Asynchronous injection is also well established.
|
|
72
|
+
But when you are **blending** the two in the same container, it requires a little care.
|
|
73
|
+
|
|
74
|
+
### `get` vs `resolve`
|
|
75
|
+
|
|
76
|
+
Think of `get(X)` / `resolve(X)` as a request not just for `X`, but for the entire tree of objects `X` depends on.
|
|
77
|
+
`get` is only safe when every node in that tree is already settled.
|
|
78
|
+
|
|
79
|
+
| Condition | When to use |
|
|
80
|
+
|---|---|
|
|
81
|
+
| All dependencies are synchronous, **or** async singletons are already resolved | `container.get(X)` |
|
|
82
|
+
| Any dependency in the tree may still be pending | `await container.resolve(X)` |
|
|
83
|
+
|
|
84
|
+
> **Tip:**
|
|
85
|
+
> Call `resolveSingletons(true)` after your last `bindXXX` call and before any `get` call to avoid hard-to-debug timing issues.
|
|
86
|
+
|
|
87
|
+
**When a dependency must do async work before it is usable** — open a database connection, load remote config, etc. — there are two ways to handle it:
|
|
106
88
|
|
|
107
|
-
|
|
89
|
+
#### **Async factory** — bind an async factory that performs the initialization and returns the ready instance:
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
108
92
|
container.bindAsyncFactory(SharedService, async () => {
|
|
109
|
-
|
|
110
|
-
return
|
|
93
|
+
const svc = new SharedService();
|
|
94
|
+
return svc.connect(); // returns Promise<SharedService>
|
|
111
95
|
}).asSingleton();
|
|
112
96
|
|
|
113
|
-
// A
|
|
114
|
-
container.bindClass(TransactionHandler);
|
|
115
|
-
|
|
116
|
-
// Wait for all bound asynchronous factory functions to complete.
|
|
117
|
-
// This step is optional. You could omit and use Container.resolve instead (see alternative below).
|
|
97
|
+
// Option A — resolve everything up front, then use get() as normal
|
|
118
98
|
await container.resolveSingletons(true);
|
|
119
|
-
// We are now connected to the database
|
|
120
|
-
|
|
121
|
-
// In our request processing code...
|
|
122
99
|
const tx = container.get(TransactionHandler);
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
```typescript
|
|
100
|
+
|
|
101
|
+
// Option B — resolve on demand
|
|
126
102
|
const tx = await container.resolve(TransactionHandler);
|
|
127
103
|
```
|
|
128
104
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
105
|
+
> **Note:**
|
|
106
|
+
> A factory takes full responsibility for constructing and initializing its object — `@PostConstruct` is not called on factory-returned instances.
|
|
107
|
+
> `bindFactory` and `bindAsyncFactory` are therefore the right choice when you need complete control over how an object is built, or when you cannot annotate the class.
|
|
108
|
+
|
|
109
|
+
#### **`@PostConstruct`** — mark an initialization method to run on the fully constructed object after the constructor returns.
|
|
110
|
+
The method can be synchronous or asynchronous, which is especially useful since a class constructor can never be async.
|
|
111
|
+
It is also useful because a base class constructor cannot call methods overridden by a subclass.
|
|
112
|
+
The method can have parameters which can be annotated with `@Inject` and `@Optional` — the container resolves and injects them before calling the method.
|
|
113
|
+
This lets you avoid storing dependencies from the constructor solely for post-construction use:
|
|
135
114
|
|
|
136
|
-
## @PostConstruct Support
|
|
137
|
-
It is not always possible to fully initialize your object in the class constructor.
|
|
138
|
-
This (albeit contrived) demo shows that the `Employee` class is not yet initialized when the `Person` subclass tries to call the overridden `state` method.
|
|
139
115
|
```typescript
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
constructor(private manager: boolean) { super(); }
|
|
147
|
-
protected state() { return this.manager ? "busy" : "producing"; }
|
|
116
|
+
@Injectable()
|
|
117
|
+
class DatabasePool {
|
|
118
|
+
@PostConstruct()
|
|
119
|
+
async init(@Inject(DbConfig) config: DbConfig): Promise<void> {
|
|
120
|
+
this.pool = await createPool(config); // config is injected, not stored
|
|
121
|
+
}
|
|
148
122
|
}
|
|
149
|
-
// This will print:
|
|
150
|
-
// "Hi I'm 'producing", even though the author probably expected
|
|
151
|
-
// "Hi I'm busy", because they passed true for the 'manager' parameter.
|
|
152
|
-
new Employee(true);
|
|
153
123
|
```
|
|
154
|
-
Can we refactor code to work around this? Sure. You may have to submit a couple of PR's, re-write legacy code that has no unit tests, trash encapsulation, skip a few nights sleep, etc. But why?
|
|
155
|
-
A PostConstruct annotation ensure's your initialization method is working on a fully constructed version of your object.
|
|
156
|
-
Even better, since constructors cannot be asynchronous, PostConstruct gives you an easy way to asynchronously prepare an object before it's put into service.
|
|
157
124
|
|
|
158
|
-
|
|
159
|
-
|
|
125
|
+
> **Important:**
|
|
126
|
+
> Always explicitly declare the return type (`void` or `Promise<void>`, never leave it to be inferred).
|
|
127
|
+
> `container.get()` will throw if the return type is missing and the method actually does return a Promise.
|
|
128
|
+
> Constructor and `@PostConstruct` parameters follow the same rules: class-typed params are auto-resolved by reflected type; use `@Inject` for interface or primitive types. Use `@Optional()` with no argument to pass `undefined` if you want to allow a JS parameter default.
|
|
160
129
|
|
|
161
|
-
|
|
162
|
-
class A {
|
|
163
|
-
public constructor() { }
|
|
130
|
+
## Scopes
|
|
164
131
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
public init(): void { ... }
|
|
168
|
-
}
|
|
169
|
-
class D {
|
|
170
|
-
public constructor() { }
|
|
132
|
+
Create isolated or hierarchical scopes using multiple containers.
|
|
133
|
+
A child container searches its own bindings first, then walks up the parent hierarchy:
|
|
171
134
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
public init(): Promise<void> { ... }
|
|
175
|
-
}
|
|
135
|
+
```typescript
|
|
136
|
+
const child = new Container(parent);
|
|
176
137
|
```
|
|
177
138
|
|
|
178
|
-
|
|
179
|
-
- Ensure your post construction method signature properly **declares** it's return type.
|
|
180
|
-
**WARNING!** An unspecified return type signature where the type is implied by `return new Promise(...)` is not sufficient! You must explicitly declare the return type.
|
|
181
|
-
- `Container.get` will throw an exception if you try to retrieve a class with `@PostConstruct` on a method that returns a `Promise`, but which does not **declare** it's return type to be `Promise`.
|
|
182
|
-
- The library will not invoke @PostConstruct on an object returned from a factory. It is the factory's responsibility to construct and initialize before returning.
|
|
183
|
-
- You will likely want a `Container.resolveSingletons(true)` call between your last `Container.bindXXX()` call and any `Container.get` call.
|
|
184
|
-
|
|
185
|
-
## API Overview
|
|
186
|
-
Async-Injection tries to follow the common API patterns found in most other DI implementations. Please refer to the examples above or the linked elements below for specific syntax.
|
|
187
|
-
- The
|
|
188
|
-
[Container](https://pcafstockf.github.io/async-injection/api-docs/container.html) class implements a
|
|
189
|
-
[Binder](https://pcafstockf.github.io/async-injection/api-docs/binder.html) interface, which allows you to bind a
|
|
190
|
-
[Constant](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindconstant),
|
|
191
|
-
[Factory](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindfactory),
|
|
192
|
-
[AsyncFactory](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindasyncfactory), or
|
|
193
|
-
[Class](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindclass) value to an
|
|
194
|
-
[InjectableId](https://pcafstockf.github.io/async-injection/api-docs/globals.html#injectableid) (aka key) within a
|
|
195
|
-
[Container](https://pcafstockf.github.io/async-injection/api-docs/container.html).
|
|
196
|
-
- The
|
|
197
|
-
[Container](https://pcafstockf.github.io/async-injection/api-docs/container.html) also implements an
|
|
198
|
-
[Injector](https://pcafstockf.github.io/async-injection/api-docs/injector.html) interface which allows you to synchronously
|
|
199
|
-
[get](https://pcafstockf.github.io/async-injection/api-docs/container.html#get) or asynchronously
|
|
200
|
-
[resolve](https://pcafstockf.github.io/async-injection/api-docs/container.html#resolve) anything that has been bound.
|
|
201
|
-
- When binding a
|
|
202
|
-
[Factory](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindfactory),
|
|
203
|
-
[AsyncFactory](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindasyncfactory) or
|
|
204
|
-
[Class](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindclass) to an
|
|
205
|
-
[InjectableId](https://pcafstockf.github.io/async-injection/api-docs/globals.html#injectableid), you can chain the result of the call to specify the binding as a
|
|
206
|
-
[Singleton](https://pcafstockf.github.io/async-injection/api-docs/bindas.html#assingleton), and/or configure an
|
|
207
|
-
[Error Handler](https://pcafstockf.github.io/async-injection/api-docs/bindas.html#onerror).
|
|
208
|
-
- Containers may be nested by passing a parent Container to the
|
|
209
|
-
[constructor](https://pcafstockf.github.io/async-injection/api-docs/container.html#constructor) of a child Container.
|
|
210
|
-
- To bind a
|
|
211
|
-
[Class](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindclass) into the
|
|
212
|
-
[Container](https://pcafstockf.github.io/async-injection/api-docs/container.html), you must add the
|
|
213
|
-
[@Injectable](https://pcafstockf.github.io/async-injection/api-docs/globals.html#injectable) decorator (aka annotation) to your class (see examples above).
|
|
214
|
-
- You may optionally add a
|
|
215
|
-
[@PostConstruct](https://pcafstockf.github.io/async-injection/api-docs/globals.html#postconstruct) decorator to a method of your class to perform synchronous or asynchronous initialization of a new instance.
|
|
216
|
-
- By default, Async-Injection will examine the parameters of a class constructor and do it's best to match those to a bound
|
|
217
|
-
[InjectableId](https://pcafstockf.github.io/async-injection/api-docs/globals.html#injectableid).
|
|
218
|
-
- You may use the
|
|
219
|
-
[@Inject](https://pcafstockf.github.io/async-injection/api-docs/globals.html#inject) decorator to explicitly declare which
|
|
220
|
-
[InjectableId](https://pcafstockf.github.io/async-injection/api-docs/globals.html#injectableid) should be used (generally required for a
|
|
221
|
-
[Constant](https://pcafstockf.github.io/async-injection/api-docs/container.html#bindconstant) binding as in the logLevel example above).
|
|
222
|
-
- The
|
|
223
|
-
[@Optional](https://pcafstockf.github.io/async-injection/api-docs/globals.html#optional) decorator allows you to specify a default value for a class constructor parameter in the event that no matching
|
|
224
|
-
[InjectableId](https://pcafstockf.github.io/async-injection/api-docs/globals.html#injectableid) can be found.
|
|
225
|
-
- The Container's
|
|
226
|
-
[resolveSingletons](https://pcafstockf.github.io/async-injection/api-docs/container.html#resolvesingletons) method may be used to wait for any bound (a)synchronous [Singletons](https://en.wikipedia.org/wiki/Singleton_pattern) to finish initialization before continuing execution of your application.
|
|
139
|
+
## IoC modules
|
|
227
140
|
|
|
228
|
-
|
|
229
|
-
|
|
141
|
+
No special module system needed — TypeScript's own `import` is your module system. Create a file, import your container, and register your bindings.
|
|
142
|
+
|
|
143
|
+
## API
|
|
144
|
+
|
|
145
|
+
A Container's life follows a simple arc: *configure* it by registering bindings, *activate* it so async singletons can initialize, then *use* it to retrieve objects.
|
|
230
146
|
|
|
231
|
-
|
|
147
|
+
#### Configure
|
|
232
148
|
|
|
233
|
-
|
|
149
|
+
| | |
|
|
150
|
+
|---|----------------------------------------------------------------|
|
|
151
|
+
| `new Container(parent?)` | Create a container; optionally inherit bound ids from a parent |
|
|
152
|
+
| `bindConstant(id, value)` | Bind a fixed value |
|
|
153
|
+
| `bindClass(id, class?)` | Bind a class (requires `@Injectable`) |
|
|
154
|
+
| `bindFactory(id, fn)` | Bind a synchronous factory function |
|
|
155
|
+
| `bindAsyncFactory(id, fn)` | Bind an asynchronous factory function |
|
|
156
|
+
| `.asSingleton()` | Chain: share one instance across the Container |
|
|
157
|
+
| `.onError(cb)` | Chain: handle construction errors |
|
|
234
158
|
|
|
235
|
-
|
|
159
|
+
#### Activate
|
|
236
160
|
|
|
237
|
-
|
|
161
|
+
| | |
|
|
162
|
+
|---|---|
|
|
163
|
+
| `resolveSingletons(true)` | Await all async singleton initializations |
|
|
164
|
+
|
|
165
|
+
#### Use
|
|
166
|
+
|
|
167
|
+
| | |
|
|
168
|
+
|---|---|
|
|
169
|
+
| `get(id)` | Synchronously retrieve a bound value |
|
|
170
|
+
| `resolve(id)` | Asynchronously retrieve a bound value (see [`get` vs `resolve`](#get-vs-resolve)) |
|
|
171
|
+
|
|
172
|
+
#### Annotate your classes
|
|
173
|
+
|
|
174
|
+
| | |
|
|
175
|
+
|---|---|
|
|
176
|
+
| `@Injectable()` | Required on any class bound with `bindClass` |
|
|
177
|
+
| `@Inject(id)` | Explicitly declare which id to inject into a constructor parameter |
|
|
178
|
+
| `@Optional(default?)` | Provide a fallback if the id is not bound; omit the argument to let a JS parameter default apply |
|
|
179
|
+
| `@PostConstruct()` | Mark a method to run after full construction (sync or async); parameters annotated with `@Inject`/`@Optional` are injected by the container |
|
|
180
|
+
| `@Release()` | Mark a method to call when a singleton is released |
|
|
181
|
+
| `InjectionToken<T>` | Create a typed token for binding interfaces or primitives |
|
|
182
|
+
|
|
183
|
+
## Acknowledgements
|
|
238
184
|
|
|
239
|
-
|
|
185
|
+
Inspired by [InversifyJS](https://github.com/inversify/InversifyJS), [NestJS async providers](https://docs.nestjs.com/fundamentals/async-providers), [Darcy Rayner's DI walkthrough](https://dev.to/darcyrayner/typescript-dependency-injection-in-200-loc-12j7), and Carlos Delgado's [QueryablePromise](https://ourcodeworld.com/articles/read/317/how-to-check-if-a-javascript-promise-has-been-fulfilled-rejected-or-resolved) idea.
|
|
240
186
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
187
|
+
## Support Resources
|
|
188
|
+
The [`support/`](./support) directory contains supplementary guides that are **not** part of the library itself:
|
|
189
|
+
- [`lazy-loading/`](./support/lazy-loading.md) — patterns for on-demand, split-bundle DI module loading
|
|
190
|
+
- [`react-integration/`](./support/react-integration.md) — using with React applications, including scoped child containers and testing patterns
|
|
191
|
+
- [`migrate-from-inversify/`](./support/migrate-from-inversify/ReadMe.md) — shim files and a two-phase migration guide for InversifyJS users
|
|
192
|
+
- [`migrate-from-tsyringe/`](./support/migrate-from-tsyringe.md) — migration guide for TSyringe users
|
|
193
|
+
- [`migrate-from-typedi/`](./support/migrate-from-typedi.md) — migration guide for TypeDI users
|
|
247
194
|
|
|
248
|
-
|
|
249
|
-
copies or substantial portions of the Software.
|
|
195
|
+
## License
|
|
250
196
|
|
|
251
|
-
|
|
252
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
253
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
254
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
255
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
256
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
257
|
-
SOFTWARE.
|
|
197
|
+
[MIT](./License.txt) © 2020–2024 Frank Stock
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { BindableProvider } from './bindable-provider
|
|
2
|
-
import { AsyncFactory } from './
|
|
3
|
-
import { InjectableId, Injector } from './injector
|
|
4
|
-
import { State } from './state
|
|
1
|
+
import { BindableProvider } from './bindable-provider';
|
|
2
|
+
import { AsyncFactory } from './binding';
|
|
3
|
+
import { InjectableId, Injector } from './injector';
|
|
4
|
+
import { State } from './state';
|
|
5
5
|
/**
|
|
6
6
|
* @inheritDoc
|
|
7
7
|
* This specialization invokes it's configured Factory asynchronously and waits until it can provide the result.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { AsyncFactory, BindAs, OnErrorCallback, OnSuccessCallback, SyncFactory } from './
|
|
2
|
-
import { ClassConstructor, InjectableId, Injector } from './injector
|
|
3
|
-
import { Provider } from './provider
|
|
1
|
+
import { AsyncFactory, BindAs, OnErrorCallback, OnSuccessCallback, SyncFactory } from './binding';
|
|
2
|
+
import { ClassConstructor, InjectableId, Injector } from './injector';
|
|
3
|
+
import { Provider } from './provider';
|
|
4
4
|
/**
|
|
5
5
|
* @inheritDoc
|
|
6
6
|
* This abstraction is for Providers that can be additionally configured as Singletons and/or configured with error and/or success handling callback(s).
|
|
@@ -21,7 +21,7 @@ export declare abstract class BindableProvider<T, M = ClassConstructor<T> | Sync
|
|
|
21
21
|
*/
|
|
22
22
|
protected errorHandler?: OnErrorCallback<T, any>;
|
|
23
23
|
/**
|
|
24
|
-
* Invoked by the
|
|
24
|
+
* Invoked by the Container to create chain-able configuration
|
|
25
25
|
*
|
|
26
26
|
* @see BindAs
|
|
27
27
|
*/
|
package/lib/binding.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { ClassConstructor, InjectableId, Injector } from './injector';
|
|
2
|
+
/**
|
|
3
|
+
* Type definition for functions that return a value.
|
|
4
|
+
* The function should return a valid value, but may throw an exception if it cannot.
|
|
5
|
+
*/
|
|
6
|
+
export type SyncFactory<T> = (injector: Injector) => T;
|
|
7
|
+
/**
|
|
8
|
+
* Type definition for functions that return a Promise for a value.
|
|
9
|
+
* The function *must* not throw and must return a valid Promise (e.g. pending, resolved, rejected).
|
|
10
|
+
*/
|
|
11
|
+
export type AsyncFactory<T> = (injector: Injector) => Promise<T>;
|
|
12
|
+
/**
|
|
13
|
+
* You may bind an error handler which will be invoked if the bound InjectableId could not be put into service.
|
|
14
|
+
* An error handler *must* not throw, but may return an Error that will be propagated back up the call chain.
|
|
15
|
+
*
|
|
16
|
+
* @param injector The Injector that experienced the error.
|
|
17
|
+
* @param id The identifier for what was trying to be made.
|
|
18
|
+
* @param maker The thing that made (or tried to make) the value. Will be one of type ClassConstructor, SyncFactory, or AsyncFactory, depending on how you registered the binding.
|
|
19
|
+
* @param error Identifies the problem that occurred.
|
|
20
|
+
* @param value If the 'maker' was able to create the thing, but it had an error during post construction, the made thing will be passed here.
|
|
21
|
+
* @returns one of 3 results...
|
|
22
|
+
* A substitute thing (kind of like a 'maker' do-over) which must be fully operational (e.g. any `@PostConstruct` will be ignored).
|
|
23
|
+
* An alternate Error which will be propagated back up the call chain.
|
|
24
|
+
* Undefined, which means the 'error' parameter will be propagated back up the call chain.
|
|
25
|
+
*/
|
|
26
|
+
export type OnErrorCallback<T, M = unknown> = (injector: Injector, id: InjectableId<T>, maker: M, error: unknown, value?: T) => T | Error | void;
|
|
27
|
+
/**
|
|
28
|
+
* You may bind a success handler which will be invoked just before the bound InjectableId is put into service.
|
|
29
|
+
* This is an alternative to the more preferred `@PostConstruct` decorator for scenarios when usage of that decorator is not feasible.
|
|
30
|
+
* WARNING:
|
|
31
|
+
* By registering a success handler, you override and nullify any `@PostConstruct` decorator on the class.
|
|
32
|
+
* In such a scenario, the success handler should perform whatever care and feeding the class expected from the `@PostConstruct` decorator.
|
|
33
|
+
* A success handler *must* not throw, but may return an Error that will be propagated back up the call chain.
|
|
34
|
+
*
|
|
35
|
+
* @param value The thing that was made.
|
|
36
|
+
* @param injector The Injector that performed the construction.
|
|
37
|
+
* @param id The identifier for what was made.
|
|
38
|
+
* @param maker The thing that made. Will be one of type ClassConstructor, SyncFactory, or AsyncFactory, depending on how you registered the binding.
|
|
39
|
+
* @returns one of 3 results...
|
|
40
|
+
* An Error which will be propagated back up the call chain.
|
|
41
|
+
* Undefined, which means the object is ready to be placed into service.
|
|
42
|
+
* A Promise that resolves to one of the above two values (undefined or Error).
|
|
43
|
+
*/
|
|
44
|
+
export type OnSuccessCallback<T, M = unknown> = (value: T, injector: Injector, id: InjectableId<T>, maker: M) => Promise<Error | void> | Error | void;
|
|
45
|
+
/**
|
|
46
|
+
* Descriptor object used with {@link Container.register} to specify how an id should be bound.
|
|
47
|
+
* Mirrors the TSyringe registration API.
|
|
48
|
+
*/
|
|
49
|
+
export type RegisterDescriptor<T> = {
|
|
50
|
+
useClass: ClassConstructor<T>;
|
|
51
|
+
} | {
|
|
52
|
+
useValue: T;
|
|
53
|
+
} | {
|
|
54
|
+
useFactory: SyncFactory<T>;
|
|
55
|
+
} | {
|
|
56
|
+
useAsyncFactory: AsyncFactory<T>;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* An interface allowing binding of an error handler.
|
|
60
|
+
*
|
|
61
|
+
* @see OnErrorCallback
|
|
62
|
+
*/
|
|
63
|
+
export interface BindErrHandler<T, M = unknown> {
|
|
64
|
+
onError(cb: OnErrorCallback<T, M>): void;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* An interface allowing binding of a post construction handler.
|
|
68
|
+
*
|
|
69
|
+
* @see OnSuccessCallback
|
|
70
|
+
*/
|
|
71
|
+
export interface BindHandler<T, M = unknown> extends BindErrHandler<T, M> {
|
|
72
|
+
onSuccess(cb: OnSuccessCallback<T, M>): BindErrHandler<T, M>;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* @inheritDoc
|
|
76
|
+
* This specialization also allows you to specify that the binding is 'Singleton' (e.g. only one in the system).
|
|
77
|
+
*/
|
|
78
|
+
export interface BindAs<T, M = unknown> extends BindHandler<T, M> {
|
|
79
|
+
asSingleton(): BindHandler<T, M>;
|
|
80
|
+
}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.AsyncFactoryBasedProvider = void 0;
|
|
4
|
-
const
|
|
5
|
-
const
|
|
4
|
+
const bindable_provider_1 = require("./bindable-provider");
|
|
5
|
+
const state_1 = require("./state");
|
|
6
6
|
/**
|
|
7
7
|
* @inheritDoc
|
|
8
8
|
* This specialization invokes it's configured Factory asynchronously and waits until it can provide the result.
|
|
9
9
|
*/
|
|
10
|
-
class AsyncFactoryBasedProvider extends
|
|
10
|
+
class AsyncFactoryBasedProvider extends bindable_provider_1.BindableProvider {
|
|
11
11
|
constructor(injector, id, maker) {
|
|
12
12
|
super(injector, id, maker);
|
|
13
13
|
}
|
|
@@ -19,8 +19,8 @@ class AsyncFactoryBasedProvider extends bindable_provider_js_1.BindableProvider
|
|
|
19
19
|
let retVal = this.singleton;
|
|
20
20
|
if (!retVal) {
|
|
21
21
|
// Wrap the async factory's Promise in an errorHandler aware Promise.
|
|
22
|
-
// Our contract is that an AsyncFactory may not throw and must return a valid Promise (e.g
|
|
23
|
-
retVal =
|
|
22
|
+
// Our contract is that an AsyncFactory may not throw and must return a valid Promise (e.g., pending, resolved, rejected, etc).
|
|
23
|
+
retVal = state_1.State.MakeState(this.makePromiseForObj(this.maker(this.injector), obj => obj));
|
|
24
24
|
}
|
|
25
25
|
if (this.singleton === null)
|
|
26
26
|
this.singleton = retVal;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-factory-provider.js","sourceRoot":"","sources":["../../src/async-factory-provider.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"async-factory-provider.js","sourceRoot":"","sources":["../../src/async-factory-provider.ts"],"names":[],"mappings":";;;AAAA,2DAAqD;AAGrD,mCAA8B;AAE9B;;;GAGG;AACH,MAAa,yBAA6B,SAAQ,oCAAoC;IACrF,YAAY,QAAkB,EAAE,EAAmB,EAAE,KAAsB;QAC1E,KAAK,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;;OAGG;IACH,cAAc;QACb,IAAI,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC;QAC5B,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,qEAAqE;YACrE,+HAA+H;YAC/H,MAAM,GAAG,aAAK,CAAC,SAAS,CAAI,IAAI,CAAC,iBAAiB,CAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAC/F,CAAC;QACD,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI;YAC1B,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC;QACzB,OAAO,MAAM,CAAC;IACf,CAAC;CACD;AApBD,8DAoBC","sourcesContent":["import {BindableProvider} from './bindable-provider';\nimport {AsyncFactory} from './binding';\nimport {InjectableId, Injector} from './injector';\nimport {State} from './state';\n\n/**\n * @inheritDoc\n * This specialization invokes it's configured Factory asynchronously and waits until it can provide the result.\n */\nexport class AsyncFactoryBasedProvider<T> extends BindableProvider<T, AsyncFactory<T>> {\n\tconstructor(injector: Injector, id: InjectableId<T>, maker: AsyncFactory<T>) {\n\t\tsuper(injector, id, maker);\n\t}\n\n\t/**\n\t * @inheritDoc\n\t * This specialization invokes it's configured Factory and provides the result (or invokes the error handler if necessary).\n\t */\n\tprovideAsState(): State<T> {\n\t\tlet retVal = this.singleton;\n\t\tif (!retVal) {\n\t\t\t// Wrap the async factory's Promise in an errorHandler aware Promise.\n\t\t\t// Our contract is that an AsyncFactory may not throw and must return a valid Promise (e.g., pending, resolved, rejected, etc).\n\t\t\tretVal = State.MakeState<T>(this.makePromiseForObj<T>(this.maker(this.injector), obj => obj));\n\t\t}\n\t\tif (this.singleton === null)\n\t\t\tthis.singleton = retVal;\n\t\treturn retVal;\n\t}\n}\n"]}
|