Initializing RavenDB in MVC4 with StructureMap
I hear more and more .Net devs are starting to get into the world of NoSQL, partly in thanks to the insanely awesome product, RavenDb (from the builders of RhinoMocks and NHibernate Profiler). I feel pretty strongly this is one of the biggest contributions to .Net web developers since MVC.
So, I want to share a very simple/clean way to initialize the RavenDB DocumentStore (on app start) and ALSO the DocumentSession (on each Http Request) using a popular IoC (Inversion of Control) container called StructureMap.
Here’s how it works:
1. Create a new MVC4 project (I’m using the empty template) and use NuGet to install the RavenDB client and StructureMap from the package manager console.
PM> Install-Package RavenDB.Client -pre
PM> Install-Package StructureMap.MVC4
2. Even though RavenDb is very simple to install locally, try out RavenHQ and get yourself a free db. All you will need is the connection string (under ‘Manage’) after you create a db.
3. Add the RavenDb connection string to your web.config, like so:
<add name="Raven" connectionString="Url=https://2.ravenhq.com/databases/your-db; ApiKey=your-api-key" />
4. Find the IoC.cs file and add these 2 “Initialize expressions”.
5. Now, just add a Controller which accepts IDocumentSession in the constructor and you’re all set. Like so:
I personally don’t mind having the IDocumentSession in each of my controllers if the project isn’t too large. But there are some other ways to handle this, like a base controller or a ActionFilter, but I may have a forthcoming post on that as well.
If you have any feedback why you like\dislike this approach, I would love to hear your thoughts.
Remember, keep it simple…but not simpler.