microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.18k stars 172 forks source link

How to pass parameters to a class #184

Closed hmajid2301 closed 3 years ago

hmajid2301 commented 3 years ago

Sorry if this has been asked already,

Lets say I have a class like so, which needs to receive some x parameters, in this case to connect to a database.

export class RoomRepository {
  constructor(username: string, password: string, host: string, port: number, dbName: string, authDB: string) {
    super(username, password, host, port, dbName, authDB);
  }

How can I use this in conjunction with this library? How can I inject this class with the correct values ?

Thanks

MeltingMosaic commented 3 years ago

There are a couple of ways to do this - if you have a mixture of resolvable and non-resolvable parameters @autoinjectable will allow you to specify some values, and resolve the remainder. In your case though, it looks like you have all non-resolvable values, in which case, what I have typically see done, is that you manually instantiate the object and register it with the container, so that anyone that depends on this class will receive the instance you have created. If you must make this resolvable from the container, you will need to use @inject-with-transform() on each parameter to provide the values. It's messy, and seems painful, but it's why the feature was added :).