我是使用 RavenDB 的新手。我的理解是我们必须首先创建一个 DocumentStore,然后打开一个会话才能将数据保存到数据库中。从文档中,我了解到我们不应该每次都创建实例,而应该只使用单例来创建 DocumentStore。但我意识到大多数文档或教程每次都只是演示创建实例。
仅供参考,我正在使用 ASP.NET MVC 框架。
所以我的问题来了,
- 应将 CreatingDocumentStore.cs(单例类)放在哪个文件夹中?在应用程序文件夹的根目录中?
- 创建了这个单例类之后,如何使用呢?
下面是我的 AdminController 在使用 Singleton 之前的原始代码。而且我不知道如何更改它以使用单例类-CreatingDocumentStore.cs
如果有人可以通过显示代码演示使用 Singleton,我将不胜感激。提前致谢!
Controller 文件夹中的AdminController.cs
public class AdminController : Controller
{
public ActionResult Index()
{
using (var store = new DocumentStore
{
Url = "http://localhost:8080/",
DefaultDatabase = "foodfurydb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
session.Store(new Restaurant
{
RestaurantName = "Boxer Republic",
ResCuisine = "Western",
ResAddress = "Test Address",
ResCity = "TestCity",
ResState = "TestState",
ResPostcode = 82910,
ResPhone = "02-28937481"
});
session.SaveChanges();
}
}
return View();
}
public ActionResult AddRestaurant()
{
return View();
}
}
在根文件夹中创建DocumentStore.cs
public class CreatingDocumentStore
{
public CreatingDocumentStore()
{
#region document_store_creation
using (IDocumentStore store = new DocumentStore()
{
Url = "http://localhost:8080"
}.Initialize())
{
}
#endregion
}
#region document_store_holder
public class DocumentStoreHolder
{
private static Lazy<IDocumentStore> store = new Lazy<IDocumentStore>(CreateStore);
public static IDocumentStore Store
{
get { return store.Value; }
}
private static IDocumentStore CreateStore()
{
IDocumentStore store = new DocumentStore()
{
Url = "http://localhost:8080",
DefaultDatabase = "foodfurydb"
}.Initialize();
return store;
}
}
#endregion
}