Skip to content

Use async methods #470

@remojansen

Description

@remojansen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions