-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Guidance for async dependencies #1
Comments
Hey Thank you! Since tinioc gives you whatever comes back from your factory then you can just return a promise. // dbClient.ts
import { Client } from "pg";
/**
* Creates and connects a pg client
*/
const getConnectedClient = async () => {
const client = new Client();
await client.connect();
return client;
};
/*
I'd recommend to move the `Promise<Client>` type to the bindings file
for decoupling benefits
*/
const client = getConnectedClient();
export const dbClient = (): Promise<Client> => client; This essentially gives you an async component, since the component is a promise. Good question btw, I'll make note to add a section about this to the readme. |
Sry, accidentally closed it prematurely :/ |
I've updates the readme and example too 👍 |
That's what I was afraid of 😁 That every async dependency will need to be resolved manually. This is the same design that An interesting approach is taken by the The reason I am concerned about this, is because the design requires one of the two solutions, both of which I find to be not so elegant: Solution 1: Resolve manuallyfunction useCase() {
const client = await getConnectedClient();
} Solution 2: Use bootstrap function for container buildingasync function bootstrap() {
const client = new Client();
const db = await client.connect();
container.bind<bindings.DB>(bindings.DB, db);
return container
}
await bootstrap().then((container) => {
// app code goes here
}) |
I think the async injection (resolve manually) solution is actually quite elegant as it conveys very clearly what's happening. It is an async dependency so you're injecting it async too. You just have to make sure not to inject at component creation, else your component will also become async. Another approach would be to hide the asynchronicity in the actual method call. For example, you can hide the DB connection promise inside the I hope this helps |
I'll close this since it seems inactive. |
Looks like a nice and clean ioc implementation.
Wondering about binding async dependencies?
For example a pg database connection.
Should it be resolved prior to binding then? Would be nice to have that documented and maybe added to the example repo.
Thank you.
The text was updated successfully, but these errors were encountered: