Inject RavenDB DocumentStore and DocumentSession

Jun 27, 2012 at 9:38 AM
Edited Jun 27, 2012 at 9:51 AM

Hi :)

With RavenDB, you must have a DocumentStore singleton instance and then lots of DocumentSession instances percall or transient.

Then, I tryed to make something like this:  

IDocumentStore store = new DocumentStore { Url = "http://localhost:8080"};


_currentContainer.RegisterInstance<IDocumentSession>(store.OpenSession(), new PerResolveLifetimeManager());

But it doesn't work.

Exception is: InvalidOperationException - The current type,
Raven.Client.IDocumentSession, is an interface and cannot be
constructed. Are you missing a type mapping?

This works: 

IDocumentStore store = new DocumentStore { Url = "http://localhost:8080"};


_currentContainer.RegisterType<IDocumentSession>(new InjectionFactory

(c => store.OpenSession()));



 But I don't know why, could someone explain me the differences, please?

Thanks a lot :) 

Jun 27, 2012 at 9:52 AM

RegisterInstance stores a single instance of the IDocumentSession in the PerResolveLifetimeManager. That instance is basically thrown away after the first resolve that needs to create a session. But no new instance will be created afterwards.

Using InjectionFactory will recreate a new instance of an IDocumentSession using the provided factory delegate whenever such a session is needed.

Jun 27, 2012 at 10:04 AM

Then, using this InjectionFactory I will have a singleton instance of DocumentStore and a per web request DocumentSession instance?


Thank you very much :)

Jun 27, 2012 at 10:15 AM

That depends on where you create that DocumentStore in your application and what lifetime you chose when you register your IDocumentSession.

Unity does not have a PerWebRequestLifetimeManager. But if you search the web you will find quite a few solutions that use an HttpContext-backed implementation to overcome that shortcoming. You have to use that lifetime when registering IDocumentSession.

Wether your DocumentStore is a singleton depends on where you create it. As it is not registered with the container you have to manage its lifetime yourself.

Jun 27, 2012 at 10:22 AM

Thanks a lot mate :)