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.