Injection Token with Factory Provider

Explain how to use factory providers with an InjectionToken to dynamically create services.
import { InjectionToken, Provider } from '@angular/core';

// Define an InjectionToken for the service
export const MY_SERVICE_TOKEN = new InjectionToken('MyService');
This code snippet defines an injection token using the Angular InjectionToken API. The token is used to inject a service into components or other services without directly referencing the service class.
// The actual service you want to inject
class MyService {
  constructor(private config: any) {}
  // Service methods here

// Factory function that creates an instance of MyService
function myServiceFactory(config: any) {
  // Here you might have more complex logic for creating the service
  return new MyService(config);
This snippet defines a simple service class `MyService` and a factory function `myServiceFactory`. The factory function is responsible for creating an instance of `MyService` with some configuration.
// Assume we have some config object
const serviceConfig = { /* ... */ };

// Define the factory provider for the InjectionToken
const MY_SERVICE_PROVIDER: Provider = {
  provide: MY_SERVICE_TOKEN,
  useFactory: () => myServiceFactory(serviceConfig),
  // Add any dependencies the factory might need here
  // deps: [SomeOtherService]
This snippet contains the configuration object which will be passed to the service. It also creates a provider object using the previously defined InjectionToken and the factory function. The provider tells Angular's dependency injection system how to create the service.
import { NgModule } from '@angular/core';

  providers: [
    // Other providers here
  // Other module metadata properties here
export class MyModule {}
In this final snippet, we have an Angular module that declares the provider in its `providers` array. Including `MY_SERVICE_PROVIDER` here makes the service available to the rest of the application.