我建议使用自定义 Ninject Provider 来设置您的 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 成为单例。我建议您在需要与 RavenDB 交互时在 Ninject 提供的 IDocumentStore 实例上使用 OpenSession() 简单地创建一个新的 IDocumentSession。IDocumentSession 对象非常轻量级,遵循工作单元模式,不是线程安全的,并且可以在需要的地方使用和快速处理。
正如其他人所做的那样,您还可以考虑实现一个基本 MVC 控制器,该控制器覆盖 OnActionExecuting 和 OnActionExecuted 方法以分别打开会话和保存更改。