RavenDB with IoC/DI - IDocumentStore or I(Async)DocumentSession?

Viewed 432

I googled a bit and searched this forum before posting this, since I presumed it had been beaten to death - but since I didn't see any results that seemed clearly asking this, I figured I'd give it a shot. There's a pretty high chance it's been answered before, but I didn't stumble upon a clear page about it.

When using dependency injection, which is considered the better practice? Injecting the entire IDocumentStore and then spawning a session from it as needed, or injecting the appropriate IDocumentSession or IAsyncDocumentSession?

In the past, I've injected IAsyncDocumentSession everywhere - but it's come up that I actually need to use a non async session in a few places. This got me to thinking if I was just approaching injecting Raven wrong altogether.

So, using the IDocumentStore might be like ...

public AsHandler(IDocumentStore store) { RavenStore = store; }

private IDocumentStore RavenStore { get; set; }

public async Task Handle() {
   using(var session = RavenStore.OpenAsyncSession()) {
      ... // do stuff with an async session
   }
}

But then the more specific session usecases would appear such as ...

public AsHandler(IAsyncDocumentSession session) { RavenSession = session; }

private IAsyncDocumentSession RavenSession { get; set; }

public async Task Handle() {
   // do stuff with an async session
}

or respectively ...

public AsHandler(IDocumentSession session) { RavenSession = session; }

private IDocumentSession RavenSession { get; set; }

public async Task Handle() {
   // do stuff with a non-async session
}

Is there even any difference other than preference? My initial thought is that using the IDocumentSession and IAsyncDocumentSession is better lifecycle management, but I could be wrong.

I am using .NET Core 2.0.3 with StructureMap with Raven DB 4.0 (40023) specifically, but I would posit that this could apply to any configuration and any version.

1 Answers

Not sure this has changed with 4.0 but so far the creation of the DocumentStore was considered a rather expensive/heavy operation and therefore the suggested approach is to create it only once per application (singleton; for futher details please see RavenDb Documentation).

Sessions on the other hand are rather cheap to create and therefore can be created as needed.

You could still inject both objects (store and session) with DI and just use different lifecycles (singleton vs. transient).

Of course you can also setup DI to provide either the sync- or the asnyc-version of the session as needed.

Related