Skip to content
pedroreys edited this page Apr 16, 2012 · 1 revision

RavenDB and WebApi

WebContribApi provides the functionality to manage RavenDb sessions through the RavenActionFilter class located in WebApiContrib.RavenDb.ActionFilters namespace. By using it you don't have to manage the creation and disposal of your IDocumentSession instance. One will be created for every request and disposed (with SaveChanges being called before) at the end.

There are two main ways you can use it:

Decorating a controller

You can decorate a controller with the RavenActionFilter as illustrated below:

[RavenActionFilter("RavenDB")]
public class ProductsController : ApiController
{
	public IDocumentStore Session { get; set; }
}

Where "RavenDB" is the name of a connection string entry in your web.config file containing the address of the server. Every controller using the action filter, needs algo, a public property with IDocumentStore type. This property (Session in our sample) will receive the opened session ready to use.

Registering the filter in Global filters

By registering the filter in the Global.asax file all your controllers will receive the IDocumentSession instance. This is a good way to make sure all your application has the session instance available. Please note that you also need the IDocumentStore property in all your controllers. Here is a sample:

//Global.asax file
protected void Application_Start()
{
	var raven = new RavenActionFilterAttribute(new Uri("http://localhost:8080"));
	GlobalConfiguration.Configuration.Filters.Add(raven);
	
	//rest of your initialization code...
}

This time we used the other constructor available. It receives an instance of the System.Uri class instead of the connection string name.

Make sure you add the filter to the global configuration of the Http namesapce instead of just the Mvc. To do that you have to access the filters collection through the GlobalConfiguration object.

Troubleshooting

If you encounter any problems when using this Api or plain Raven Db, make sure that both you client and server are running the same version.