I’ve been dabbling with Nancy and RavenDB and here is my implementation notes when trying to find the best way to initialize RavenDB’s DocumentStore and DocumentSession in Nancy.
My inspiration was this blog post. The guiding principle is to rely as much as possible on Nancy’s TinyIoC.
First I put the connection settings into the project’s config file.
ConfigureApplicationContainer is overridden to register IDocumentStore with application scope (one instance of IDocumentStore for the entire application). Generation of the DocumentStore is handled by the factory method GenerateRavenDocStore. Later I will decrypt the encrypted API key within GenerateRavenDocStore.
ConfigureRequestContainer is also overridden to register IDocumentSession with request scope (one instance of IDocumentSession for each HTTP request).
With this setting, I can use IDocumentSession in a module like so.
IDocumentSession is one of the module’s constructor arguments. In the constructor, IDocumentSession is saved to an instance variable so it is available to route handlers.
I prefer to call SaveChanges explicitly from within route handlers. Another option is to call SaveChanges automatically at the end of each request by using after request hook. Maybe with something like this.