我推薦使用自定義Ninject提供程序來設置您的RavenDB DocumentStore。首先將它放置在註冊Ninject服務的代碼塊中。
kernel.Bind<IDocumentStore>().ToProvider<RavenDocumentStoreProvider>().InSingletonScope();
接下來,添加這個實現Ninject Provider的類。
public class RavenDocumentStoreProvider : Provider<IDocumentStore>
{
var store = new DocumentStore { ConnectionName = "RavenDB" };
store.Conventions.IdentityPartsSeparator = "-"; // Nice for using IDs in routing
store.Initialize();
return store;
}
的IDocumentStore需要一個單身,但不要讓IDocumentSession單身。我建議您只需在IDocumentStore實例上使用OpenSession()創建一個新的IDocumentSession,Ninject會在您需要與RavenDB進行交互時爲您提供。 IDocumentSession對象非常輕便,遵循工作單元模式,不是線程安全的,並且意圖在需要時使用並快速處理。
正如其他人做,你也可以考慮執行基礎MVC控制器,它覆蓋OnActionExecuting和OnActionExecuted方法來分別打開會話並保存更改。
+1 Ninject使每個請求的會話變得很容易,使用InRequestScope()回答http://bit.ly/HJADY3 – DalSoft 2012-04-16 11:17:31
你在哪裏調用SaveChanges()?我試圖在Application_EndRequest中做到這一點,但沒有運氣。 – Andrew 2012-09-03 09:52:58
我明確地調用了SaveChanges(),當它有意義時,不會在每個請求結束時自動調用。我不知道爲什麼你需要這樣做,或者爲什麼你有問題。我懷疑它與Ninject的操作順序和請求作用域依賴關係有關,儘管沒有一些診斷信息就沒有說明。 – 2012-09-03 13:11:06