title: NestJS inject custom TypeOrm repository based on an Interface
body: <p>I'm currently working through the database integration <a href="https://docs.nestjs.com/techniques/database#custom-repository" rel="nofollow noreferrer">docs</a> for NestJS using TypeOrm. In these docs there are examples that show how to inject a custom database repository using the app.module from NestJS. All of these examples inject classes using the actual type of the custom repository.</p>
  <pre><code>@Injectable()
  export class AuthorService {
    constructor(private authorRepository: AuthorRepository) {}
  }
  
  </code></pre>
  <p>This code is injected via the app.modules by providing a import like such:</p>
  <pre><code>@Module({
    imports: [TypeOrmModule.forFeature([AuthorRepository])],
    controller: [AuthorController],
    providers: [AuthorService],
  })
  export class AuthorModule {}
  </code></pre>
  <p>This works well if you are fine with programming against an implementation, but I prefer to use an interface in my classes. I've already found the solution to injecting classes via an interface with NestJS in a previous <a href="https://stackoverflow.com/a/63904194/6351280">question</a>, but when I try to inject my custom repository like that, it doesn't seem to instanciate correctly and becomes undefined.</p>
  <p><code>(node:16658) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'save' of undefined</code></p>
  <p>Because of this, I assume you can only inject customRepositories via the <code>forFeature()</code> call in the app.module, but that won't allow me to use interfaces for injection, as far as I know. Is there any other way I can inject a custom TypeOrm repository without having the replace all my interfaces for the implementation of my custom repository? Thanks in advance!</p>
  <p><strong>Edit</strong></p>
  <p>Here is my current code, I managed to get it to inject, but this still forces me to use the implementation instead of the interface each time I call the constructor. This is mainly an issue when testing due to mocking.</p>
  <pre><code>  @CommandHandler(FooCommand)
  export class FooHandler
    implements ICommandHandler&lt;FooCommand&gt; {
  
    private fooRepository: IFooRepository; // Using Interface as a private property.
    private barEventBus: IEventBus;
    
    constructor(fooRepository: FooRepository,
       barEventBus: EventBus) { // Forced to use implementation in constructor for injection.
      this.fooRepository = fooRepository;
      this.barEventBus = barEventBus;
    }
  </code></pre>
  <pre><code>@EntityRepository(FooEntity)
  export class FooRepository extends Repository&lt;FooEntity&gt; implements IFooRepository {
  
    getFoo() {
      // Do stuff
    }
  }
  
  </code></pre>
  <pre><code>@Module({
    imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([FooRepository]],
  
    // Other module setup
  })
  export class AppModule {}
  </code></pre>