Reputation: 926
I am currently at the beginning of the learning curve with Neo4j, so I am making a lot of assumptions about scoping for Dependency Injection (currently experimenting in a Razor Pages application).
Assumption 1: Driver is a lightweight protocol wrapper that would be safe in Singleton scope.
Assumption 2: It might be useful to scope Session to the web request lifetime. For instance, I might want to add to a transaction in some middle-ware.
Here's some example DI setup:
public void ConfigureServices(IServiceCollection services)
{
services
.AddSingleton(_ => GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "hubdb")))
.AddScoped(_ => _.GetRequiredService<IDriver>().Session())
.AddRazorPages();
}
And a trivial business object that will be wired up and injected into a PageModel class:
public class SignupVendor
{
private readonly ISession session;
public SignupVendor(ISession session)
{
this.session = session;
}
public async Task RunAsync(string name)
{
using var transaction = await session.BeginTransactionAsync();
try
{
var result = await transaction.RunAsync(
"CREATE (v:Vendor {name:$name}) RETURN v",
new { name });
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
}
Can you confirm or comment on my assumptions?
Upvotes: 3
Views: 656
Reputation: 247531
Assumption 1: Driver is a lightweight protocol wrapper that would be safe in Singleton scope.
Short Answer: Yes
From Docs
The driver object
A Neo4j client application will require a driver instance in order to provide access to the database. This driver should be made available to all parts of the application that need to interact with Neo4j. In languages where thread safety is an issue, the driver can be considered thread-safe.
A note on lifecycle
Applications will typically construct a driver instance on startup and destroy it on exit. Destroying a driver instance will immediately shut down any connections previously opened via that driver; for drivers that contain a connection pool, the entire pool will be shut down.
emphasis mine.
Assumption 2: It might be useful to scope Session to the web request lifetime. For instance, I might want to add to a transaction in some middle-ware.
Short Answer: Yes
From the Docs
Sessions
A session is a container for a sequence of transactions. Sessions borrow connections from a pool as required and so should be considered lightweight and disposable. In languages where thread safety is an issue, a session should not be considered thread-safe. In languages that support them, sessions are usually scoped within a context block. This ensures that they are properly closed and that any underlying connections are released and not leaked.
emphasis mine
Upvotes: 4