I'm currently delving into Dependency Injection with tsyringe. This is a new concept for me altogether.
The code snippet below is functional and successfully instantiates the dependencies using container.resolve(Foo)
.
import "reflect-metadata";
import { injectable, container } from "tsyringe";
class Database {
get() {
return "got-stuff-from-database";
}
}
@injectable()
class Foo {
constructor(private database: Database) {}
checkDb() {
return this.database.get();
}
}
const fooInstance = container.resolve(Foo);
console.log(fooInstance.checkDb());
//=> got-stuff-from-database
The following snippet (taken mostly from their readme) is puzzling to me. I am unable to make it work or comprehend why we need to use inject
when we already have the injectable
decorator in the previous example. It seems like everyone else understands it without any trouble.
interface Database {}
@injectable()
class Foo {
constructor(@inject("Database") private database?: Database) {}
checkDb() {
return 'stuff';
}
}
const fooInstance = container.resolve(Foo);
console.log(fooInstance.checkDb());