Skip to content

Commit

Permalink
add lifecycle in service decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
Victor Mendele committed May 5, 2021
1 parent d799b85 commit 1348dfa
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
12 changes: 7 additions & 5 deletions src/V2/Implementation/ServiceLoader.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {ContainerBuilderInterface, LifeCycle, ServiceKey, SyncServiceProviderInterface} from '../Interfaces'

export const Service = (serviceKey: ServiceKey): ClassDecorator => target => {
export const Service = (serviceKey: ServiceKey, lifeCycle: LifeCycle): ClassDecorator => target => {
// @ts-ignore
Reflect.defineMetadata('Service@ServiceKey', serviceKey, target)
Reflect.defineMetadata('Service@ServiceKey', {serviceKey, lifeCycle}, target)
}
export const Inject = (serviceKey: ServiceKey): ParameterDecorator => (target, propertyKey, parameterIndex) => {
// @ts-ignore
Expand All @@ -11,11 +11,13 @@ export const Inject = (serviceKey: ServiceKey): ParameterDecorator => (target, p
// @ts-ignore
Reflect.defineMetadata('Inject@ServiceKey', injectionTokens, target)
}

type Constructor<T> = { new(...args: any[]): T }

export const reflectServiceLoader = (services: Constructor<unknown>[]) => (containerBuilder: ContainerBuilderInterface) => {
const servicesFactories = services.map(constructor => {
// @ts-ignore
const serviceKey = Reflect.getOwnMetadata('Service@ServiceKey', constructor)
const { serviceKey, lifeCycle } = Reflect.getOwnMetadata('Service@ServiceKey', constructor)

// @ts-ignore
const injectionTokens: { [key: string]: string } = Reflect.getOwnMetadata('Inject@ServiceKey', constructor) || {}
Expand All @@ -27,8 +29,8 @@ export const reflectServiceLoader = (services: Constructor<unknown>[]) => (conta
})

return new constructor(...factoryParameters)
}]
}, lifeCycle]
})

servicesFactories.forEach(([serviceKey, factory]) => containerBuilder.addFactory(serviceKey, factory, LifeCycle.Singleton))
servicesFactories.forEach(([serviceKey, factory, lifeCycle]) => containerBuilder.addFactory(serviceKey, factory, lifeCycle))
}
5 changes: 3 additions & 2 deletions tests/V2/ReflectionContainer.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import 'reflect-metadata'
import {createContainerBuilder} from '../../src/V2/Implementation/Container'
import {Inject, reflectServiceLoader, Service} from '../../src/V2/Implementation/ServiceLoader'
import {LifeCycle} from '../../src/V2/Interfaces'

@Service("MyService")
@Service("MyService", LifeCycle.Singleton)
class MyService {}

@Service("AnotherService")
@Service("AnotherService", LifeCycle.Singleton)
class AnotherService {
constructor(
@Inject("MyService") public readonly myService: MyService
Expand Down

0 comments on commit 1348dfa

Please sign in to comment.