registerFactory Function

Module
import { registerFactory } from "@tsed/di"
Source/packages/di/src/registries/ProviderRegistry.ts

Overview

const registerFactory: (provider: any, instance?: any) =>; void;

Description

Add a new factory in the ProviderRegistry.

Example with symbol definition

import {registerFactory, InjectorService} from "@tsed/common";

export interface IMyFooFactory {
   getFoo(): string;
}

export type MyFooFactory = IMyFooFactory;
export const MyFooFactory = Symbol("MyFooFactory");

registerFactory(MyFooFactory, {
     getFoo:  () => "test"
});

// or

registerFactory({provide: MyFooFactory, instance: {
     getFoo:  () => "test"
}});

@Service()
export class OtherService {
     constructor(@Inject(MyFooFactory) myFooFactory: MyFooFactory){
         console.log(myFooFactory.getFoo()); /// "test"
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Note: When you use the factory method with Symbol definition, you must use the @Inject() decorator to retrieve your factory in another Service. Advice: By convention all factory class name will be prefixed by Factory.

Example with class

import {InjectorService, registerFactory} from "@tsed/common";

export class MyFooService {
 constructor(){}
     getFoo() {
         return "test";
     }
}

registerFactory(MyFooService, new MyFooService());
// or
registerFactory({provider: MyFooService, instance: new MyFooService()});

@Service()
export class OtherService {
     constructor(myFooService: MyFooService){
         console.log(myFooFactory.getFoo()); /// "test"
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19