Add static Context (Singleton) to DbBase

ActiveRecord pattern: expose a shared DbContext on DbBase so any
entity subclass can reach it without passing context through parameters.
The instance-level DbContext back-reference still works; the static one
provides a class-level global fallback.
This commit is contained in:
2026-09-14 20:48:21 +01:00
parent c4bfc14f32
commit 8b46fccf08
2 changed files with 34 additions and 2 deletions
+15
View File
@@ -11,6 +11,21 @@ namespace Before;
/// </summary> /// </summary>
public class DbBase public class DbBase
{ {
// -----------------------------------------------------------------
// Static singleton: an ActiveRecord-style shared context that any
// entity can reach without passing it through method parameters.
// -----------------------------------------------------------------
/// <summary>
/// Shared (singleton) <see cref="DbContext" /> accessible from every
/// entity via its base type. Set once at application startup so that
/// entity methods can call <c>DbBase.Context!</c> instead of carrying
/// a context reference.
///
/// This is yet another leak: domain objects depend on the persistence
/// layer at the *type* level, not just the instance level.
/// </summary>
public static DbContext? Context { get; set; }
/// <summary> /// <summary>
/// Primary key. Fresh (unsaved) entities have <see cref="Guid.Empty"/>; /// Primary key. Fresh (unsaved) entities have <see cref="Guid.Empty"/>;
/// <see cref="DbContext.Save"/> assigns a real id, faking EF's identity /// <see cref="DbContext.Save"/> assigns a real id, faking EF's identity
+19 -2
View File
@@ -131,8 +131,7 @@ public class BeforeTests
Assert.True(app.IsPersisted(client)); Assert.True(app.IsPersisted(client));
} }
// A companion check: a client that was never attached/saved exposes no // A companion check: a bare client has no context until saved.
// context yet, so the leak is dormant until the entity meets a context.
[Fact] [Fact]
public void A_bare_client_has_no_context_until_saved() public void A_bare_client_has_no_context_until_saved()
{ {
@@ -142,4 +141,22 @@ public class BeforeTests
Assert.Null(client.DbContext); Assert.Null(client.DbContext);
Assert.False(app.IsPersisted(client)); Assert.False(app.IsPersisted(client));
} }
// -----------------------------------------------------------------
// (8) Static Context (Singleton): DbBase exposes a class-level
// shared DbContext. Setting it makes the context accessible
// from any entity via its base type.
// -----------------------------------------------------------------
[Fact]
public void DbBase_has_a_static_Context_singleton()
{
Assert.Null(DbBase.Context); // fresh — not set yet
var db = new DbContext();
DbBase.Context = db;
Assert.Same(db, DbBase.Context);
DbBase.Context = null; // cleanup
}
} }