Using a factory method to control Angular dependency injection

Similar to the use of the useClass attribute in the previous post, we can also use the useFactory attribute to supply a factory method to create our dependent value.

To start off, here’s a simple illustration of using the useFactory attribute.

We need to create a factory method which will use some logic to determine which service should be created. In this case checking if the, which includes the time information, is even. This is of course a rather contrived example.

import { FirstService } from './first.service';
import { SecondService } from './second.service';

export let serviceFactory = () => {
  if ( % 2 === 0) {
    return new FirstService();
  } else {
    return new SecondService();

In the first service we add the useFactory attribute to the service’s decorator:

import { Injectable } from '@angular/core';
import { serviceFactory } from './service.provider';

  providedIn: 'root',
  useFactory: serviceFactory
export class FirstService {

  constructor() { }

  output() {
    return 'first';

Here is the code for SecondService:

export class SecondService implements FirstService {
  constructor() { }
  output() {
    return 'second';

And now any component that injects a FirstService through it’s constructor will use the serviceFactory method which could contain any logic we require. This could include reading the service information from a configuration file in the project, allowing us to inject different services based on which configuration file the project was built with.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s