We were asked about best practices for managing the RavenDB session (unit of work) in a .NET Core MVC application. I thought it is interesting enough to warrant its own post.
RavenDB’s client API is divided into the Document Store, which holds the overall configuration required to access a RavenDB and the Document Session, which is a short lived object implementing Unit of Work pattern and typically only used for a single request.
We’ll start by adding the RavenDB configuration to the appsettings.json file, like so:
We bind it to the following strongly typed configuration class:
The last thing to do it to register this with the container for dependency injection purposes:
We register both the Document Store and the Document Session in the container, but note that the session is registered on a scoped mode, so each connection will get a new session.
Finally, let’s make actual use of the session in a controller:
Note that we used to recommend having SaveChangesAsync run for you automatically, but at this time, I think it is probably better to do this explicitly.