Skip to content

Service Factory and IoC

Thiago Bustamante edited this page Aug 18, 2020 · 2 revisions

Service Factory and IoC

It is possible to control how Typescript Rest will instantiate your services. It is useful, for example, to integrate it with an IoC Container.

For example, to use typescript-ioc, you can install the IoC container and configure a serviceFactory to use the IoC Container. The module typescript-rest-ioc provides a factory for it.

npm install typescript-rest --save
npm install typescript-ioc --save
npm install typescript-rest-ioc --save

Then, to configure Typescript rest to use your factory, you can add a rest.config file in the root of your project:

{
  "serviceFactory": "typescript-rest-ioc"
}

Or call the method Server.registerServiceFactory directly in your code.

And now you can use Injections, Request scopes and all the features of the IoC Container. It is possible to use it with any other IoC Container, like Inversify.

Example:

class HelloService {
  sayHello(name: string) {
    return "Hello " + name;
  }
}

@Path("/hello")
class HelloRestService {
  @Inject
  private helloService: HelloService;

  @Path(":name")
  @GET
  sayHello( @PathParam('name') name: string): string {
    return this.sayHello(name);
  }
}

To create your own factory, just extends the interface ServiceFactory:

export interface ServiceFactory {
    /**
     * Create a new service object. Called before each request handling.
     */
    create: (serviceClass: Function, context: ServiceContext) => any;
    /**
     * Return the type used to handle requests to the target service.
     * By default, returns the serviceClass received, but you can use this
     * to implement IoC integrations, once some frameworks like typescript-ioc or
     * Inversify can override constructors for injectable types.
     */
    getTargetClass: (serviceClass: Function) => FunctionConstructor;
}