diff --git a/packages/core/middleware/middleware-module.ts b/packages/core/middleware/middleware-module.ts index ed7da6e1b1a..87ae234e799 100644 --- a/packages/core/middleware/middleware-module.ts +++ b/packages/core/middleware/middleware-module.ts @@ -212,23 +212,7 @@ export class MiddlewareModule { next: () => void, ) => { try { - const contextId = ContextIdFactory.getByRequest(req); - if (!req[REQUEST_CONTEXT_ID]) { - Object.defineProperty(req, REQUEST_CONTEXT_ID, { - value: contextId, - enumerable: false, - writable: false, - configurable: false, - }); - - const requestProviderValue = isTreeDurable - ? contextId.payload - : req; - this.container.registerRequestProvider( - requestProviderValue, - contextId, - ); - } + const contextId = this.getContextId(req, isTreeDurable); const contextInstance = await this.injector.loadPerContext( instance, moduleRef, @@ -325,4 +309,20 @@ export class MiddlewareModule { }, ); } + + private getContextId(request: unknown, isTreeDurable: boolean): ContextId { + const contextId = ContextIdFactory.getByRequest(request); + if (!request[REQUEST_CONTEXT_ID]) { + Object.defineProperty(request, REQUEST_CONTEXT_ID, { + value: contextId, + enumerable: false, + writable: false, + configurable: false, + }); + + const requestProviderValue = isTreeDurable ? contextId.payload : request; + this.container.registerRequestProvider(requestProviderValue, contextId); + } + return contextId; + } }