registerFactory Function

Module
import { registerFactory } from "@tsed/common"
Source/packages/common/src/di/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"
     }
}

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"
     }
}