typedi
typedi copied to clipboard
Question: Why my custom decorator injects the ContainerInstance?
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
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, 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
Ok, but is there any way to inject a custom value that is not in the container?
You need to register it first.
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?