我在Express項目中使用Inversify.JS。我想創建一個Neo4j的數據庫的連接,而這個過程有兩個OBJETS:InversifyJS:依賴於HTTP請求的實例化
- 司機對象 - 可以在整個應用程序中共享,創造一個時間只有
- 會話對象 - 每個HTTP請求應建立對駕駛員的會話,它的生命週期是一樣的HTTP請求生命週期(只要在請求結束時,連接被破壞)
沒有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();
});
感謝。