简体   繁体   中英

Nestjs - Manually instantiate a class with dependencies on useFactory

suppose I have two classes like this

@Injectable({ scope: Scope.DEFAULT })
class Service {
    
    constructor() {}
    // ...
}

@Injectable()
class OtherService {
    param: T;

    constructor(readonly service: Service, param: T) {}

    // ... 
}

And I'm triying to dinamically instantiate the last class using a factory

const otherServiceFactory = {
    provide: "TOKEN",
    scope: Scope.Request,
    useFactory: (req: Request) => {
        const param = req.headers["foo"];
        return new OtherService(/* ts expects an instance of Service here */ , param)
    },
    inject: [REQUEST]
}

As the comment said, at the moment of creating the instance ts expects, correctly, an instance of Service . The problem is I rather not mess up with the DI tree, so I don't want to instantiate Service . I was able to hack this around by setting the param later instead of asking in the constructor, so I don't need the factory anymore, but feels pretty sub-optimal. Any suggestions?

Thanks

You can add Service to the inject array, and get the instance of Service that Nest creates, then pass it to OtherService so that you have everything required to create the class.

const otherServiceFactory = {
    provide: "TOKEN",
    scope: Scope.Request,
    useFactory: (req: Request, service: Service) => {
        const param = req.headers["foo"];
        return new OtherServiceservice, param)
    },
    inject: [REQUEST, Service]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM