typedi icon indicating copy to clipboard operation
typedi copied to clipboard

Question: Why my custom decorator injects the ContainerInstance?

Open Bennjamon opened this issue 3 years ago • 4 comments

I am creating my custom decorator InjectConnection:

export default function InjectConnection(dbName: string) {
  return (object: any, propertyName: string, index: number) => {
    Container.registerHandler({
      object,
      propertyName,
      index,
      value: () => dbName,
    });
  };
}

And I am tryíng to use it in a service:

@Service()
export default class UsersDBService {
  User: Model<UserDocument>;

  constructor(@InjectConnection('users') connection: any) {
    console.log(connection);

    // this.User = connection.model<UserDocument>('user');
  }
}

But, in the console.log the ContainerInstance is printed

Bennjamon avatar Dec 09 '21 21:12 Bennjamon

The container injects itself as the last parameter for historical reasons. If you get the container for the connection parameter it seems the container could not resolve that parameter.

It's not optimal, but I think this is the reason for this behavior. (Can be wrong, I haven't touched this repo in a while)

NoNameProvided avatar Jan 13 '22 11:01 NoNameProvided

@NoNameProvided, Ok, but is there any way to inject a custom value that is not in the container? In the example, in my code I want to inject the value of dbName

Bennjamon avatar Jan 13 '22 16:01 Bennjamon

Ok, but is there any way to inject a custom value that is not in the container?

You need to register it first.

NoNameProvided avatar Jan 13 '22 16:01 NoNameProvided

You need to register it first.

I have that code:

export default function InjectConnection(dbName: string) {
  return (object: any, propertyName: string, index: number) => {
    Container.registerHandler({
      object,
      propertyName,
      index,
      value: (containerInstance) => {
        const connection = createConnection(dbName);
        console.log("Connection %s created", dbName);

        return connection;
      },
    });
  };
}

But is not working and the value method is not called, What is wrong?

Bennjamon avatar Jan 14 '22 01:01 Bennjamon