First steps with RavenDB and ASP.NET MVC with Ninject

I have been meaning to try RavenDB for more than a year now. I’m sure this blogpost duplicates lots of other intros of Raven but I’m writing this for me and I hope that it has some positive side effects for other beginners as well.

Why Raven? In my particular case, I want to have a quick way of storing and retrieving objects because I want to focus on business logic and also the client side (coffeescript, AJAX, json and the likes).

So first, install RavenDB through Nuget.This gets you also the RavenDB server so click on the executable, check localhost:8080 and go.

This is the class diagram:

Let’s get started.

This is how to connect with the RavenDB documentstore:

[code lang=”csharp”]
[TestFixtureSetUp]
public static IDocumentStore StartStore() {

var documentStore = new DocumentStore { Url = "http://localhost:8080",

DefaultDatabase = "TestDatabase"

};
documentStore.Initialize();

return documentStore;
}
[/code]

Look how easy it is to define a testdatabase. Imagine how you can run different instances next to each other.

Now let’s insert some data:

[code lang=”csharp”]
[Test]
public void Insert()
{
var documentStore = StartStore();
using (var session = documentStore.OpenSession())
{
var person = new Person {Achternaam = "Summer", Roepnaam = "Donna"};
var note = new Note {Person = person, Notitie = "Called"};
session.Store(person);
session.Store(note);
session.SaveChanges();
}

//I don’t want an Exception
Assert.Pass();
}
[/code]

And retrieve them:

[code lang=”csharp”]
[Test]
public void Retrieve()
{
var documentStore = StartStore();
using (var session = documentStore.OpenSession())
{
var person = session.Load("people/129");
var notes = session.Query().Where(y => y.Person.Id == person.Id);
//hope this fails
Assert.Null(notes);
}
[/code]

Well, this is all so simple. It’s almost not worth a blogpost. Woohoo!

Now let’s hook it up in ASP.NET MVC 3 using Ninject.

I found this to be an excellent resource, written by Dalsoft (look here).

In short: add the nuget package for Ninject:
[code lang=”csharp”]
Install-Package Ninject.MVC3
[/code]

This creates a new App_Start folder in your Web project.

Then, add a class named RavenDBNinjectModule and make it look like so:

In NinjectWebCommon you only need to add:

[code lang=”csharp”]
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new RavenDBNinjectModule());
}
[/code]

And that’s it. You’re set.

This is how to inject Raven in the Controller:

[code lang=”csharp”]

public class HomeController : Controller
{
private readonly IDocumentSession _documentSession;
public HomeController(IDocumentSession documentSession)
{
_documentSession = documentSession;
}
[/code]

I’m so impressed by the simplicity of all this.

Of course, this was just a tip of the iceberg. No, it’s the tip of the tip of iceberg. It’s the tip of the tip of the t..
You get my drift.

Follow along: here.