I'm learning DI with tsyringe. I'm also totally new to the concept of DI.
The following snippet works and the container.resolve(Foo)
properly instantiate the dependencies.
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
This is understandable. But the snippet below (mostly taken from their readme) is neither working for me nor I can understand, and nor I can understand why we need inject
when we have the above injectable
decorator. I'm sorry I searched online and found everyone is using it like everyone already know about it.
interface Database {}
@injectable()
class Foo {
constructor(@inject("Database") private database?: Database) {}
checkDb() {
return 'stuff';
}
}
const fooInstance = container.resolve(Foo);
console.log(fooInstance.checkDb());