inversify-express-utils icon indicating copy to clipboard operation
inversify-express-utils copied to clipboard

Use async methods

Open remojansen opened this issue 9 months ago • 1 comments

I'm trying to inject a database connection inRequestScope using toDynamicValue:

bind<DbClient>(DbClientSymbol)
	.toDynamicValue(async (context) => {
		const databaseConnectionManager =
			context.container.get<DatabaseConnectionManager>(
				DatabaseConnectionManagerSymbol,
			);
		return await databaseConnectionManager.getDbClient();
	})
	.inRequestScope();

Being able to do this would be awesome but I get:

Error: You are attempting to construct Symbol(DbClientSymbol) in a synchronous way but it has asynchronous dependencies.

I have been able to make it work locally but it will be a breaking change:

  1. The server.build method will become async. This is visible to end users and it is a breaking change.

  2. container.getAll becomes container.getAllAsync:

function getControllersFromContainer(container, forceControllers) {
    if (container.isBound(constants_1.TYPE.Controller)) {
        return container.getAll(constants_1.TYPE.Controller);
    }
async function getControllersFromContainer(container, forceControllers) {
    if (container.isBound(constants_1.TYPE.Controller)) {
        return container.getAllAsync(constants_1.TYPE.Controller);
    }
  1. container.getNamed becomes ``container.getNamedAsync`
// invoke controller's action
const value: unknown = await (
  httpContext.container.getNamed<Record<string, ControllerHandler>>(
    TYPE.Controller,
    controllerName,
  )[key] as ControllerHandler
)(...args);
// invoke controller's action
const value: unknown = await (
  httpContext.container.getNamedAsync<Record<string, ControllerHandler>>(
    TYPE.Controller,
    controllerName,
  )[key] as ControllerHandler
)(...args);

I tried replacing container.getNamed with container.getNamedAsync

it seems to solve the issue locally for me.

remojansen avatar Apr 02 '25 23:04 remojansen

Hey @remojansen , I don't think there's another way to go. Let's go for it. Would you like to submit a PR? Otherwise I can go for it

notaphplover avatar Apr 03 '25 18:04 notaphplover