#Token vs abstract class injection

6 messages · Page 1 of 1 (latest)

dusky bough
#

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

novel rain
#

There's no difference. The abstract class doubles as the token, so you don't need to remember the correct typ for the correct token

#

I'm also using abstract classes as interfaces for stuff I'll need to inject

#

(you don't even need the @Inject decorator that way)

#

The only possible trap there is, is if the interface (abstract class) comes from a library that somehow ends up duplicated in node_modules, there could be two different references with the same code. Then the injection won't work. But at that point you have bigger problems than that.

dusky bough
#

Super cool