microsoft / tsyringe

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

No control over execution of files #235

Open Manik2708 opened 9 months ago

Manik2708 commented 9 months ago

Describe the bug

I want to inject three dependency: Redis. So the order should be, firstly this dependency is initialized (from index.ts), then registered and finally resolved but nothing is happening this way.

To Reproduce

// in index.ts file
import "reflect-metadata";

export const client:RedisClientType=createClient({});

const connect = async():Promise<void>=>{
          client.connect()
}

// other file containing service, using this client as dependency
@singelton()
class RedisUsingService{
      private client: RedisClientType;
      constructor(@inject("RedisClient") client:RedisClientType)=>{
         this.client=client;
}
}

// in other file where registrations are hapenning: registration.ts
import {container} from "tsyringe";
import {client} from "index.ts"
container.register<RedisClientType>("RedisClient", {useValue:client});
export const redisUsingServiceInstance = container.resolve(RedisUsingService);

// This approach was leading to the error, that RedisClient is not registered this means index.ts file is not running, even if I am running ts-node index.ts
// So I initiated Redis Client in the same  registration.ts file, which solved the error
// Now I want to resolve a different object when testing which would be using testing redis client running on a different port while calling the APIs
// And here comes the problem, when I would be registering testing client in tests, APIs would still be using the object which is in
// registration.ts file and that would come from executing the whole file and registering the real client instead of testing client 

Expected behavior

Version: 4.4.0 When I am moving the export const redisUsingServiceInstance = container.resolve(RedisUsingService); in a different file, it is giving error that RedisClient is not registered. That means execution of files is very random and most probably when I run ts-node index.ts, file containing the resolved instance of service is ran before their registration. But the expectations are registration should be done before resolving the instance. Shouldn't the library ask for an entry point for the file which would be containing all the registered dependencies?