Hi ,
just wanted to make but are there key differences between injecting a token and an abstract class ?
To me the abstract class looks better in every way so did I miss any trap ?
Just to make sure we're talking about the same thing
import { ClassProvider, Inject, Injectable, Module } from '@nestjs/common';
//
// Definition
//
// Interface + Token
export const MY_ABSTRACTION_TOKEN = Symbol('whatever');
export interface MyAbstractionInterface {
handle(): Promise<void>;
}
export class MyInterfaceImpl implements MyAbstractionInterface {
handle(): Promise<void> {
return Promise.resolve();
}
}
// Abstract class
export abstract class MyAbstractionClass {
abstract handle(): Promise<void>;
}
export class MyClassImpl implements MyAbstractionClass {
handle(): Promise<void> {
return Promise.resolve();
}
}
//
// Module
//
const interfaceProvider: ClassProvider<MyAbstractionInterface> = {
provide: MY_ABSTRACTION_TOKEN,
useClass: MyInterfaceImpl,
};
const classProvider: ClassProvider<MyAbstractionClass> = {
provide: MyAbstractionClass,
useClass: MyClassImpl,
};
// Both providers in same module for brevity
@Module({
exports: [MyAbstractionClass, MY_ABSTRACTION_TOKEN],
imports: [],
providers: [interfaceProvider, classProvider],
})
export class MyModule {}
//
// Usage
//
@Injectable()
export class MyService {
constructor(
@Inject(MyAbstractionClass)
private readonly _classInjection: MyAbstractionClass,
@Inject(MY_ABSTRACTION_TOKEN)
private readonly _tokenInjection: MyAbstractionInterface
) {}
}
thanks