Apr 12

Updated 01 Oct 2012 for version 1.0.960

About a month ago now I used RavenDB for the first time in a ‘real’ application. I think it’s awesome, frictionless and easy to get up and running. However I’ve heard from fellow developers that they think there is a high barrier to entry when compared to a traditional RDBMS approach such as SQL server. Yes when learning anything new there is a learning curve, but this post is to dispel the myth that setting up RavenDB is hard and to show you what you get for pretty much zero effort.

There are two flavours of RavenDB server and embedded. I’m going to show you in this post how to set up RavenDB embedded inside your MVC application.

Prerequisites

All you need installed is MVC 3 (steps are the same for MVC 4) and NuGet.

 

Create new MVC 3 project empty template

File -> New Project -> select ASP.NET MVC 3 Web Application template -> Empty

Install Ninject NuGet package

Tools -> Library Package Manager -> Package Manager Console

PM> Install-Package Ninject

Install Ninject MVC3 NuGet package


PM> Install-Package Ninject.MVC3

Install RavenDB Embedded NuGet package


PM> Install-Package RavenDB.Embedded

Remove the reference to Raven.Client.Lightweight.FSharp unless you have F# runtime installed.

Add Ninject Module for RavenDB Embedded

Create a new class called RavenDBNinjectModule.cs and add the following code:

The first binding to IDocumentStore binds using a simple method. Using NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080) means if you are running Visual Studio as an non admin the first time you run the site you will get a UAC prompt to allow RavenDB to listen on port 8080 (default port) rather than a failure. UseEmbeddedHttpServer = true enables the RestAPI and RavenDB Management Studio. The rest of the code should be self-explanatory.

You can think of a DocumentStore as a Initialized Raven database and therefore should be created once per application, hence .InSingletonScope() You can change the configuration of the EmbeddableDocumentStore by setting properties for example DataDirectory = “new path here” check out RavenDB’s documentation for available configuration options.

The second binding to IDocumentSession again binds using a simple method that just calls OpenSession() from the initialized EmbeddableDocumentStore, this is your session to RavenDB and generally you want to work with one session per request, hence .InRequestScope()

Add your Ninject Module to NinjectWebCommon.cs

When you installed the Ninject MVC3 package you might have noticed it created a folder called App_Start. App_Start is for WebActivator and the code in this folder will run before the code in Global.asax.cs. If you don’t know about WebActivator it’s well worth reading David Ebbo’s post.

In the App_Start folder the Ninject MVC3 package created a file called NinjectWebCommon.cs. We just need to change it to load our RavenDBNinjectModule. At the bottom of the file there is a method called RegisterServices change it to the following:
private static void RegisterServices(IKernel kernel)
{
    kernel.Load(new RavenDBNinjectModule());
}

Add App_Data folder

This is optional as you can store RavenDB in any location but a good place to store RavenDB is in the App_Data folder.

RavenDB Management Studio

The last and optional task is to enable RavenDB Management Studio. RavenDB Management Studio is great and simplifies tasks such as maintaining documents, managing indexes and testing queries.

All you need to do to enable RavenDB Management Studio is copy the Silverlight Raven.Studio.xap to the root of your application. Raven.Studio.xap can be found in the packages folder. The packages folder isn't part of your Visual Studio project so you will need to find the folder in Windows Explorer.


Copy packages\RavenDB-Embedded.1.0.888\lib\net40\Raven.Studio.xap
To the root of your application

Now you can use RavenDB Management Studio by pointing a browser to http://localhost:8080

Don't forget to use UseEmbeddedHttpServer = true when initializing the DocumentStore.

Use RavenDB in your MVC application

Now we have the RavenDB bindings in Ninject MVC3, RavenDB will be available to all our controllers. So using RavenDB in our application is as trivial as creating a controller with a constructor and a IDocumentSession parameter.

For example

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

Conclusion

I hope this blog post shows that it is easy to get up and running with RavenDB in no time at all. It should also demonstrate how far you can get with just installing a couple of NuGet packages.

Based on this post I’ve spent a further 20 minutes creating an example MVC application that saves basic information about Movies. The example also shows how in your tests you can configure the EmbeddableDocumentStore to save documents in memory.

My example application is on GitHub https://github.com/DalSoft/RavenDBInFiveMinutes and can also be downloaded as a zip file.

I also videoed the 20 minutes or so I spent creating the example application.

21 Responses to “MVC – Get RavenDB up and running in 5 minutes using Ninject”

  1. Can’t seem to find RavenDBNinjectModule.cs code.

  2. Naveen says:

    Sine you have real time experience, can you share your experience using RavenDB? (why custom chose this DB, how different it is from SQL Server or Oracle, some highlights about the issues you face with RevenDB )

  3. Ethan says:

    Get a error stating that

    Error 1 ‘Ninject.IKernel’ does not contain a definition for ‘Get’ and no extension method ‘Get’ accepting a first argument of type ‘Ninject.IKernel’ could be found (are you missing a using directive or an assembly reference?) C:\Work\RavenDB\Raven\Raven\App_Start\RavenDBNinjectModule.cs 25 73 Raven

    on Line

    Bind().ToMethod(context => context.Kernel.Get(IDocumentStore).OpenSession()).InRequestScope();

    • DalSoft says:

      Hi Ethan,

      Try adding using Ninject; to the code. There is a full working example on GitHub https://github.com/DalSoft/RavenDBInFiveMinutes

      • Bjarkeck says:

        Thank you :) That fixed it for me

      • Bjarkeck says:

        Hi Dalsoft thank your for your guide.

        I get this error when initialising the page for the first time:

        “Cannot load Counter Name data because an invalid index was read from the registry”
        Linje 21: return documentStore.Initialize();

        I Used MVC 4, and here is what i did differently:
        i got an error when installing RavenDb Embedded with the console, so i did it from NuGet, and that worked fine.

        My Raven.Studio.xap was not located in \lib\net40\ but in \tools

        Other then that, everything was the same.

        Hope you can help :)

  4. jacqueline says:

    Good post. I referred to it in a blogpost. Thanks!

  5. dhyah says:

    It’s better to write a implement with sqlserver , so we can switch different database in web.config. that’ the benefit using Ninject .

  6. Avin says:

    dude,

    I went through ur youtube video.Sad to say, it lacks sound. Did n’t anybody reported this before?

    Regards,
    Avin

    • DalSoft says:

      Hi Avin,

      The video doesn’t have any commentary this time. Although it does show step by step how I created the example.

      • Derick says:

        I’m using MVC4 and I was using RavenDB 1 and this all worked great. I upgraded to RavenDB 2.0 and I am getting an HttpListenerException on documentStore.Initialize() saying “The process cannot access the file because it is being used by another process”. I’m wondering if anyone else has had this issue.

        • DalSoft says:

          Sounds like the port is clashing with another port on your machine. Try changing the port does it work?

          NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);

          Also try removing that line completely, but this will stop the RavenDB Studio running.

  7. Nikolay says:

    Hi Darren,

    Very neat post! I have one question: Ayende suggests that the Session object needs to be destroyed after it’s been used. I see, you open session upon http request. However, I don’t see a place where the the session is getting destroyed. Any advice on that?

  8. One suggestion would adding the XAP as a linked resource instead of copying it so any update-package will do the right things:

    Right click the project, Add/Add Existing Item.. dialog, navigate down to the packages directory and back up to RavenDB/tools and then select the XAP (single click), then click the drop-arrow ON the Add button and choose Add As Link. Poof, now the single xap file is what is referenced and deployed (make sure the properties of the xap is Content).

  9. Mistic6 says:

    Hello DalSoft,

    Have you tried this in a MVC 4 / 4.5 Framework app?

Leave a Reply

preload preload preload