In graphql-modules, Singleton providers cannot directly access operation-scoped services or the GraphQL context object because they are instantiated only once. To bridge this gap, you can use the @ExecutionContext property decorator.
When you decorate a property with @ExecutionContext(), the library automatically injects the current GraphQL ExecutionContext (which includes both the GraphQL Context and the Operation-scoped Injector) into that property during the execution of a GraphQL operation.
This pattern allows singletons to remain high-performance (instantiated once) while still being able to access request-specific data or operation-scoped dependencies via this.context.injector.get(TOKEN) or this.context.context.
import { Injectable, ExecutionContext } from 'graphql-modules'
import { Config } from './config'
@Injectable()
export class Data {
constructor(private config: Config) {}
@ExecutionContext()
private context: ExecutionContext
someMethod() {
console.log('Environment', this.config.env)
// Accessing an operation-scoped service via the injector
const value = this.context.injector.get(SOME_TOKEN)
}
}