Skip to content

Commit cc378cd

Browse files
committed
fix(di): should get instance by token if @Inject param decorator used
1 parent c601a84 commit cc378cd

File tree

2 files changed

+34
-9
lines changed

2 files changed

+34
-9
lines changed

src/core/scope/utils.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { InjectableFactory } from '@asuka/di'
1+
import { InjectableFactory, Inject } from '@asuka/di'
22
import { Request } from 'express'
33

44
import { ConstructorOf } from '../types'
@@ -25,16 +25,29 @@ export function createOrGetInstanceInScope<T>(constructor: ConstructorOf<T>, sco
2525
}
2626

2727
function createInstanceInScope<T>(constructor: ConstructorOf<T>, scope: Scope): T {
28-
const constructorParams: ConstructorOf<any>[] =
28+
const paramTypes: ConstructorOf<any>[] =
2929
Reflect.getMetadata('design:paramtypes', constructor) || []
3030

31+
// parameters decorated by @Inject
32+
const paramAnnotations = Reflect.getMetadata('parameters', constructor) || []
33+
3134
const sameScopeParams: number[] = Reflect.getMetadata(SameScopeMetadataKey, constructor) || []
32-
const deps = constructorParams.map((paramConstructor, index) => {
35+
36+
const deps = paramTypes.map((type, index) => {
3337
if (sameScopeParams[index]) {
34-
return createOrGetInstanceInScope(paramConstructor, scope)
35-
} else {
36-
return InjectableFactory.getInstance(paramConstructor)
38+
return createOrGetInstanceInScope(type, scope)
3739
}
40+
41+
if (paramAnnotations[index] !== null) {
42+
let metadata: any[] = paramAnnotations[index]
43+
metadata = Array.isArray(metadata) ? metadata : [metadata]
44+
const inject: Inject | undefined = metadata.find((factory) => factory instanceof Inject)
45+
if (inject && inject.token) {
46+
return InjectableFactory.getInstanceByToken(inject.token)
47+
}
48+
}
49+
50+
return InjectableFactory.getInstance(type)
3851
})
3952

4053
const newInstance = new constructor(...deps)

test/specs/hooks.spec.tsx

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable } from '@asuka/di'
1+
import { Injectable, ValueProvider, Inject } from '@asuka/di'
22
import * as React from 'react'
33
import { act, create, ReactTestInstance, ReactTestRenderer } from 'react-test-renderer'
44
import { Observable } from 'rxjs'
@@ -16,10 +16,22 @@ enum CountAction {
1616
MINUS = 'minus',
1717
}
1818

19-
@Injectable()
19+
const numberProvider: ValueProvider = {
20+
provide: 'token',
21+
useValue: 0,
22+
}
23+
24+
@Injectable({
25+
providers: [numberProvider],
26+
})
2027
class Count extends Ayanami<State> {
2128
defaultState = {
22-
count: 0,
29+
count: -1,
30+
}
31+
32+
constructor(@Inject(numberProvider.provide) number: number) {
33+
super()
34+
this.defaultState.count = number
2335
}
2436

2537
@Reducer()

0 commit comments

Comments
 (0)