I am a newbie in using RavenDB. What I understand is we must first create a DocumentStore, then opening a session in order to save data to the database. From the documentation, I understand that we should not create instance every time and should only use singleton for creating DocumentStore. But I realized most of the documentation or tutorials only demo creating instance every time.
FYI, I'm using ASP.NET MVC framework.
So here comes my question,
- In what folder should CreatingDocumentStore.cs (Singleton class) be placed? In the root of the application folder?
- After creating this singleton class, how to use it?
Below is the original code of my AdminController before using Singleton. And I don't know how to change it in order to use the singleton class - CreatingDocumentStore.cs
I would greatly appreciate if someone can demo in using Singleton by showing the code. Thanks in advance!
AdminController.cs in Controller folder
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();
}
}
CreatingDocumentStore.cs in root folder
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
}
As Ayende posted on his blog sometime ago Managing RavenDB Document Store startup:
He show us an example:
Where you are going to place it, depends on your architecure. Usually we place
database
connections, etc, in anInfrastructure
. If you have a single project, you can place in the root of the project, or create a folder that containsdatabase
stuff.You can check these posts from stackoverflow:
How to make RavenDB DocumentStore available to calling APIs
RavenDB- Building Session Factory, singleton DocumentStore
Singleton for Embeded RavenDb