2017-07-28 65 views
0

我在Express項目中使用Inversify.JS。我想創建一個Neo4j的數據庫的連接,而這個過程有兩個OBJETS:InversifyJS:依賴於HTTP請求的實例化

  1. 司機對象 - 可以在整個應用程序中共享,創造一個時間只有
  2. 會話對象 - 每個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(); 
}); 

感謝。

回答

0

我看到你的問題的兩種解決方案。

  1. 使用inRequestScope()DbDriver依賴。 (自4.5.0版本起可用)。如果您爲一個http請求使用單個組合根,它將起作用。換句話說,每個http請求只需撥打container.get()一次。
  2. 創建子容器,將其附加到response.locals._container並將DbDriver註冊爲單身。

    let appContainer = new Container() 
    appContainer.bind(SomeDependencySymbol).to(SomeDependencyImpl); 
    
    function injectContainerMiddleware(request, response, next) { 
        let requestContainer = appContainer.createChildContainer(); 
        requestContainer.bind<DbDriver>("DbDriver").toConstantValue(new Neo4JDbDriver()); 
        response.locals._container = requestContainer; 
        next(); 
    } 
    
    express.use(injectContainerMiddleware); //insert injectContainerMiddleware before any other request handler functions 
    

在這個例子中,你可以從response.locals._containerinjectContainerMiddleware之後註冊的任何請求處理程序/中間件功能檢索DbDriver,你會得到的DbDriver

相同的情況下這是可行的,但我不確定它的性能如何。此外,我猜你可能需要在完成http請求後以某種方式處置requestContainer(解除所有依賴關係併除去對父容器的引用)。