I am using inversify, inversify-binding-decorators, and inversify-express-utlis and have problem with express middleware.
I am calling my middleware in this way:
let server = new InversifyExpressServer(container);
...
server.setConfig((app) => {
app.use(validateSession);
});
...
This is my class for ioc registration. Please notice that here I manually register SessionContext in request scope
import DatabaseApi from './../repositories/databaseApi';
import { Container, inject } from "inversify";
import TYPES from "./types";
import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators";
import { SessionContext } from './../services/session/sessionContext';
let container = new Container();
container.bind<SessionContext>(TYPES.SessionContext).to(SessionContext).inRequestScope();
let provide = makeProvideDecorator(container);
let fluentProvider = makeFluentProvideDecorator(container);
let provideNamed = (identifier: any, name: any) => {
return fluentProvider(identifier)
.whenTargetNamed(name)
.done();
};
export { container, autoProvide, provide, provideNamed, inject };
Now in my middleware I want to get my SessionContext in request scope service in this way:
export async function validateSession(req: Request, res: Response, next: NextFunction) {
try {
...
let sessionContext = container.get<SessionContext>(TYPES.SessionContext);
...
return next();
}
catch (err) {
next(err);
}
}
Service is resolved, but the problem is that if I resolve him in other place I am getting other instance. In request scope doesn't work when I use service inside express middleware. Always resolve gives new instance here. In other words - I want to start scope from express middleware. What I feel is that scope starts later from inversify-express-utils controller.
from InversifyJS - Inject service to express middleware
No comments:
Post a Comment