Skip to content

Commit

Permalink
feat(di): injectable now accept InjectableOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
LongYinan committed Jun 29, 2020
1 parent 2b11477 commit f1da08f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
22 changes: 22 additions & 0 deletions packages/di/src/__tests__/injectable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,4 +304,26 @@ describe('injectable specs', () => {
const service = newInjector.getInstance(Service)
expect(service.dep).toBe(1)
})

it('should be able to inject provider via InjectableConfigs', () => {
@Injectable()
class Dep {}

const token = new InjectionToken<Dep>('whatever')

@Injectable({
providers: [
{
useClass: Dep,
provide: token,
},
],
})
class Service {
constructor(@Inject(token) public dep: Dep) {}
}

expect(rootInjector.getInstance(Service).dep instanceof Dep).toBeTruthy()
expect(rootInjector.getInstance(Service).dep).toBe(rootInjector.getInstance(Dep))
})
})
10 changes: 9 additions & 1 deletion packages/di/src/injectable.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { rootInjector } from './root-injector'
import { Provider } from './type'

export function Injectable() {
export interface InjectableOptions {
providers: Provider[]
}

export function Injectable(options?: InjectableOptions) {
return function (target: any) {
rootInjector.addProvider({
useClass: target,
provide: target,
})
for (const provider of options?.providers ?? []) {
rootInjector.addProvider(provider)
}
return target
}
}

0 comments on commit f1da08f

Please sign in to comment.