我在一个与Express的项目中使用Inversify.JS。我想要创建一个到Neo4J数据库的连接,这个过程有两个objets:
如果没有Insersify.JS,这个问题可以使用一个简单的算法来解决:
exports.getSession = function (context) { // 'context' is the http request
if(context.neo4jSession) {
return context.neo4jSession;
}
else {
context.neo4jSession = driver.session();
return context.neo4jSession;
}
};(例子:https://github.com/neo4j-examples/neo4j-movies-template/blob/master/api/neo4j/dbUtils.js#L13-L21)
要为驱动程序创建静态依赖项,我可以注入一个常量:
container.bind<DbDriver>("DbDriver").toConstantValue(new Neo4JDbDriver());
如何在每个请求中创建一个仅实例化一次的依赖项,并从容器中检索它们?
我怀疑我必须在这样的中间件上调用容器:
this._express.use((request, response, next) => {
// get the container and create an instance of the Neo4JSession for the request lifecycle
next();
});提前谢谢。
发布于 2017-12-07 22:30:20
我看到了两种解决你问题的方法。
inRequestScope()依赖项使用DbDriver。(见4.5.0版)。如果您对一个http请求使用单一组合根,它将工作。换句话说,您只在每个http请求中调用container.get()一次。response.locals._container,并将DbDriver注册为单例。
让appContainer.bind(SomeDependencySymbol).to(SomeDependencyImpl);函数appContainer =新容器() injectContainerMiddleware (请求、响应,下一步){ let requestContainer = appContainer.createChildContainer();response.locals._container = requestContainer;next();} express.use(injectContainerMiddleware);//在任何其他请求处理函数之前插入injectContainerMiddleware在本例中,您可以在任何在DbDriver之后注册的请求处理程序/中间件函数中从response.locals._container中检索injectContainerMiddleware,您将得到DbDriver的相同实例。
这是可行的,但我不知道它的表演效果如何。此外,我猜您可能需要在完成http请求之后以某种方式释放requestContainer (取消绑定所有依赖项并删除对父容器的引用)。
https://stackoverflow.com/questions/45378966
复制相似问题