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 Date.now() is even. This is of course a rather contrived example.

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

export let serviceFactory = () => {
  if (Date.now() % 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';

@Injectable({
  providedIn: 'root',
  useFactory: serviceFactory
})
export class FirstService {

  constructor() { }

  output() {
    return 'first';
  }
}

Here is the code for SecondService:

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

Now any component that injects a FirstService through it’s constructor will use the serviceFactory method. This factory could read 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:

WordPress.com Logo

You are commenting using your WordPress.com 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