thiagobustamante / typescript-ioc

A Lightweight annotation-based dependency injection container for typescript.
MIT License
526 stars 64 forks source link

Generic Type not working #67

Open minawalphonce opened 4 years ago

minawalphonce commented 4 years ago

I m trying to register a generic type

Container.bind(Repository<Entity>)

repository is an abstract class and holds multiple implementations for each entity. I got an error

Value of type 'typeof Repository' is not callable. Did you mean to include 'new'?

I tried factory but still cant do it or there a way to do that ?

Kampfmoehre commented 4 years ago

I think the problem is, that the generic information does not exist at runtime, so in your js the entity information is missing and only the repository part remains. Repository refers to the class Repository from typeorm (that also exists in js) whereas Repository<Entity> refers to the type - a construct that only exists in typescript. What you need is a unique repository only for one entity that exists in JS and can therefore be injected anywhere.

We also struggle with integrating typeorm with typescript-ioc but found no good solution yet.

What works is the approach explained above, to have unique repositories. Something like this (note DatabaseService is a wrapper we wrote around typeorm that handles the connection):

export class CustomerRepository extends Repository<Customer> {}

const customerFactory: ObjectFactory = () => Container.get(DatabaseService).connection.getRepository(Customer);

export function registerRepositores(): void {
  Container.bind(CustomerRepository).factory(customerFactory);
}

Of course this takes away the advantage of having a generic repository because you have to write this for each repository you want to inject.