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:
@@ -11,6 +11,21 @@ namespace Before;
|
||||
/// </summary>
|
||||
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>
|
||||
/// Primary key. Fresh (unsaved) entities have <see cref="Guid.Empty"/>;
|
||||
/// <see cref="DbContext.Save"/> assigns a real id, faking EF's identity
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user