A factory function provider in Angular can have dependencies using the deps property.

@NgModule({
providers: [
{
provide: SOME_INJECTION_TOKEN,
deps: [MyService],
useFactory: (myService: myService) => {
return myService.someMethod();
},
},
],
})
export class MyModule {}

The problem is that you need to write the dependencies twice: once for the deps property and once as arguments of the useFactory function. Thanks to the new inject() function in Angular 14 there is now a better way to inject dependencies.

Call the inject() function and pass your dependency (here MyService) as argument. It will provide you the dependency and the return value is type-safe.

import { inject } from "@angular/core";

@NgModule({
providers: [
{
provide: SOME_INJECTION_TOKEN,
useFactory: () => {
const myService = inject(MyService);
return myService.someMethod();

// Or as a one-liner:
// return inject(MyService).someMethod();
},
},
],
})
export class MyModule {}