Skip to main content

What are factory services?

Factory services are services created not directly through a class but via a factory function.

That is, instead of the usual useClass, useFactory is used:

typescript
providers: [ { provide: MyService, useFactory: (dep: OtherService) => new MyService(dep.config), deps: [OtherService] } ]

This lets you:

  • control exactly how the object is created (e.g. depending on the environment or settings);
  • return different instances of the same type under different conditions;
  • inject dependencies manually through the deps parameter.

Essentially, a factory service is a way to flexibly control the creation of dependencies in DI.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.