From 8b46fccf08e2ea514aa26083e2a3e17a236174c7 Mon Sep 17 00:00:00 2001 From: Willem van den Ende Date: Mon, 14 Sep 2026 20:48:21 +0100 Subject: [PATCH] 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. --- src/Before/DbBase.cs | 15 +++++++++++++++ tests/BeforeAfter.Tests/BeforeTests.cs | 21 +++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/Before/DbBase.cs b/src/Before/DbBase.cs index b4120fa..af99ebd 100644 --- a/src/Before/DbBase.cs +++ b/src/Before/DbBase.cs @@ -11,6 +11,21 @@ namespace Before; /// public class DbBase { + // ----------------------------------------------------------------- + // Static singleton: an ActiveRecord-style shared context that any + // entity can reach without passing it through method parameters. + // ----------------------------------------------------------------- + /// + /// Shared (singleton) accessible from every + /// entity via its base type. Set once at application startup so that + /// entity methods can call DbBase.Context! 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. + /// + public static DbContext? Context { get; set; } + /// /// Primary key. Fresh (unsaved) entities have ; /// assigns a real id, faking EF's identity diff --git a/tests/BeforeAfter.Tests/BeforeTests.cs b/tests/BeforeAfter.Tests/BeforeTests.cs index 0aace98..d9d94dc 100644 --- a/tests/BeforeAfter.Tests/BeforeTests.cs +++ b/tests/BeforeAfter.Tests/BeforeTests.cs @@ -131,8 +131,7 @@ public class BeforeTests Assert.True(app.IsPersisted(client)); } - // A companion check: a client that was never attached/saved exposes no - // context yet, so the leak is dormant until the entity meets a context. + // A companion check: a bare client has no context until saved. [Fact] public void A_bare_client_has_no_context_until_saved() { @@ -142,4 +141,22 @@ public class BeforeTests Assert.Null(client.DbContext); 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 + } } \ No newline at end of file