Injecting request/response into services, repositories or other container managed entities. #8107
-
Super busy trying to ship something using Loopback 4... and haven't really been able to grok the code or step through to understand everything about the DI system. However.. I do need quick answer and help please! :) I've run into the a few times in a few spots... how can we inject
Help is much appreciated! A bit of an urgent need on this! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
The request/response object can only be injected to a controller/service/... with |
Beta Was this translation helpful? Give feedback.
-
It seems that this is happening at startup. It works on Controllers as they are instantiated on a per-request basis, meaning that the binding is already populated by the time the Controller instance is created. In contrast, Services, Components, etc. are instantiated on startup by default. This means that no HTTP request is active at the time the binding is being resolved, hence why it's throwing that error. A quick fix would be to use Getters: // Imports
import {Getter, inject} from '@loopback/rest';
import {Request, RestBindings} from '@loopback/rest';
...
// Constructor / Property / Method dependency injection
@inject.getter(RestBindings.Http.REQUEST) protected reqGetter: Getter<Request>;
...
// Inside an async function that's called only during a HTTP Request-Response cycle
const req = await reqGetter() A more long-term fix would be to reconsider not passing the raw request object to the server/component/etc., and instead have the Controller filter and pass only what's necessary. |
Beta Was this translation helpful? Give feedback.
It seems that this is happening at startup. It works on Controllers as they are instantiated on a per-request basis, meaning that the binding is already populated by the time the Controller instance is created. In contrast, Services, Components, etc. are instantiated on startup by default. This means that no HTTP request is active at the time the binding is being resolved, hence why it's throwing that error.
A quick fix would be to use Getters: