Repository navigation
Provider: Neo4j and MemGraph
The reference provider. Speaks Cypher over Bolt via the official Neo4j .NET driver. MemGraph speaks the same protocol and dialect, so a single UseMemGraph(...) overload (planned — see issue #16) will reuse the same provider stack.
The eager form takes the connection URI directly:
using Microsoft.Extensions.DependencyInjection;
using Neo4j.Driver;
using OnixLabs.ElementFramework;
services.AddGraphContext<BlogGraphContext>(builder =>
builder.UseNeo4j(
new Uri("bolt://localhost:7687"),
AuthTokens.Basic("neo4j", "password")));The lazy form takes a factory — useful when the endpoint isn't known at registration time (Testcontainers, dynamic config, secret-rotation):
services.AddGraphContext<BlogGraphContext>(builder =>
builder.UseNeo4j(
() => new Uri(Environment.GetEnvironmentVariable("NEO4J_URI")!),
AuthTokens.Basic("neo4j", Environment.GetEnvironmentVariable("NEO4J_PASSWORD")!)));The SP-aware overload lets the provider pull ILoggerFactory from the container:
services.AddGraphContext<BlogGraphContext>((sp, builder) =>
builder
.UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
.UseNeo4j(new Uri("bolt://localhost:7687"), AuthTokens.Basic("neo4j", "password")));UseLoggerFactory must come before UseNeo4j — the provider reads the factory at composition time to build its own typed loggers.
A process-wide ConcurrentDictionary<(Uri, IAuthToken), IDriver>. The Neo4j driver is itself a connection-pool — caching the driver process-wide means every AddGraphContext against the same endpoint shares one pool.
The cache has no eviction API. In production with a stable endpoint set this is fine. In test runs against Testcontainers (which assign random ports per container), it leaks one driver per port until process exit — flagged in issue #5.
CypherEmitter produces idiomatic Cypher for each provider-contract operation. Examples:
// EmitAdd<Author>
CREATE (n:Author { id: $id, name: $name, joinedAt: $joinedAt, bio: $bio })
// EmitFindById<Author>
MATCH (n:Author { id: $id }) RETURN n
// EmitExists<Author>
MATCH (n:Author { id: $id }) RETURN count(n) AS count
// EmitConnect<Author, Wrote, Post>
MATCH (s:Author { id: $startId }), (e:Post { id: $endId })
CREATE (s)-[r:Wrote { writtenAt: $writtenAt }]->(e)
// EmitTraversal for a 2-segment pattern returning the end node
MATCH (a:Author)-[w:Wrote]->(p:Post) WHERE a.name = $p0 RETURN pIdentifier escaping (backticks, reserved-word table) lives in CypherIdentifier. Parameter accumulation lives in ParameterBinder. Value flattening (Guid → string, DateTimeOffset → ISO-8601, enum → name) lives in PropertySerializer.
The executor opens an IAsyncSession (or reuses the ambient session if a transaction is active), runs the statement, and streams rows from the resulting IResultCursor. The async path is a real async iterator — the cursor and session are held via await using for the lifetime of the enumerator. The sync path drains the same stream eagerly via GetAwaiter().GetResult().
Deadlock vector. The sync surface bridges to async via GetAwaiter().GetResult(). Under hosts that capture a synchronization context (ASP.NET Classic, WinForms, WPF), this deadlocks. ASP.NET Core, console, and modern hosted-service consumers are unaffected. See issue #3 for the planned Roslyn analyzer mitigation.
Neo4jGraphTransactionOpener.Open() borrows a session, begins an IAsyncTransaction on it, wraps both in Neo4jGraphTransaction, and stores the wrapper as the ambient transaction. Commit/Rollback drive the underlying IAsyncTransaction. Dispose without explicit terminal performs best-effort rollback and logs at Warning.
One ambient transaction at a time per opener. Calling Open() twice without a terminal between throws GraphTransactionAlreadyActiveException.
Rows arrive as Neo4j INode / IRelationship entities (or scalars). Neo4jResultMaterializer walks the registered IPropertyMetadata list and copies each mapped property from the entity's Properties dictionary into a new CLR instance. Conversions cover the inverse of PropertySerializer: ISO-8601 string → DateTimeOffset / DateTime, hyphenated string → Guid, member-name string → enum, primitive widening via Convert.ChangeType (currently locale-sensitive — issue #10).
Instantiation prefers parameterless constructors (compiled Expression.New cached per type). Falls back to RuntimeHelpers.GetUninitializedObject when none exists — this fallback is being removed in favor of an explicit error at model-build time (issue #11).
MemGraph (https://memgraph.com/) speaks Bolt with the same openCypher dialect that Neo4j 5.x accepts, with a few caveats:
-
Index syntax differs.
CREATE INDEX ON :Label(prop)instead of Neo4j'sCREATE INDEX FOR (n:Label) ON (n.prop). The framework doesn't currently emit index DDL (that's the schema-migrations story in issue #18), so this doesn't affect the conformance suite today. - Transaction semantics are slightly more permissive in MemGraph (auto-commit allows multi-statement; explicit transactions are similar to Neo4j's).
-
MERGE ... ON CREATE SET / ON MATCH SETbehaves identically.
When the dedicated UseMemGraph(...) overload ships, it will reuse the same CypherEmitter, CypherIdentifier, ParameterBinder, PropertySerializer, and Neo4jResultMaterializer — the only thing that differs is the wiring extension and an optional Bolt-version constraint on the driver. Both providers will live in OnixLabs.ElementFramework.Neo4j to share the implementation.
All conformance tests pass against neo4j:5.27-community via Testcontainers. No tests are skipped — Neo4j's openCypher accepts the framework's raw-statement test corpus directly.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Neo4j.Driver;
using OnixLabs.ElementFramework;
ServiceCollection services = new();
services.AddLogging(builder => builder.AddConsole());
services.AddGraphContext<BlogGraphContext>((sp, builder) =>
builder
.UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
.UseNeo4j(
new Uri("bolt://localhost:7687"),
AuthTokens.Basic("neo4j", "password")));
await using ServiceProvider provider = services.BuildServiceProvider();
using IServiceScope scope = provider.CreateScope();
BlogGraphContext context = scope.ServiceProvider.GetRequiredService<BlogGraphContext>();
Author ada = new() { Id = Guid.NewGuid(), Name = "Ada", JoinedAt = DateTimeOffset.UtcNow };
context.Nodes<Author>().Add(ada);
await context.SaveChangesAsync();
Author? loaded = context.Nodes<Author>().FindById(ada.Id);
Console.WriteLine($"Loaded: {loaded?.Name}");