fix(centralui): no-tracking default on the circuit DbContext; mutations on their own scope (UI-1, WP5 task 5.1)

The circuit-lifetime ScadaBridgeDbContext tracked every entity a page ever
loaded, so a reload returned the first-loaded instance and never saw changes
made in another scope (Move to Site, Topology area renames, a template script
edited by the CLI/import - which a later save then silently reverted).

- CircuitDbContextTrackingHandler (CircuitHandler, registered by AddCentralUI)
  sets QueryTrackingBehavior.NoTracking on the circuit scope's context only,
  when the circuit host is built (before any component). Management-actor,
  command-transaction, HTTP-request and hosted-service scopes keep TrackAll.
- Every remaining page mutation that ran a load-modify-save service on the
  circuit context now runs it via ScopeFactory.InNewScopeAsync (fresh tracking
  context): TemplateEdit (17 TemplateService calls), Templates (5 TemplateService
  + 5 TemplateFolderService), TemplateCreate, SharedScripts, SharedScriptForm,
  TransportImport.ApplyAsync. (Sites/Topology moved in 5.2.)
- Design doc: Component-CentralUI.md 'Circuit DbContext lifetime'.

Tests: CircuitDbContextTrackingTests - handler scoping + registration, the three
finding scenarios against a real SQLite context (moved connection also asserts
the pre-fix staleness without the handler), and a source-scan guard that fails
on any mutating call through a circuit-injected load-modify-save service.
This commit is contained in:
Joseph Doherty
2026-12-03 09:52:56 -05:00
parent 2e194f4eac
commit 2969ee44e5
11 changed files with 364 additions and 44 deletions
@@ -1,5 +1,8 @@
@page "/design/shared-scripts/create"
@page "/design/shared-scripts/{Id:int}/edit"
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -278,8 +281,8 @@
if (Id.HasValue)
{
var user = await GetCurrentUserAsync();
var result = await SharedScriptService.UpdateSharedScriptAsync(
Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user);
var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.UpdateSharedScriptAsync(
Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user));
if (result.IsSuccess)
{
NavigationManager.NavigateTo("/design/shared-scripts");
@@ -292,8 +295,8 @@
else
{
var user = await GetCurrentUserAsync();
var result = await SharedScriptService.CreateSharedScriptAsync(
_formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user);
var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.CreateSharedScriptAsync(
_formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user));
if (result.IsSuccess)
{
NavigationManager.NavigateTo("/design/shared-scripts");
@@ -1,4 +1,7 @@
@page "/design/shared-scripts"
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -151,7 +154,7 @@
try
{
var user = await GetCurrentUserAsync();
var result = await SharedScriptService.DeleteSharedScriptAsync(script.Id, user);
var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.DeleteSharedScriptAsync(script.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Script '{script.Name}' deleted.");
@@ -1,4 +1,6 @@
@page "/design/templates/create"
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@@ -6,7 +8,6 @@
@using ZB.MOM.WW.ScadaBridge.TemplateEngine
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject TemplateService TemplateService
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@@ -95,10 +96,10 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.CreateTemplateAsync(
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.CreateTemplateAsync(
_createName.Trim(), _createDescription?.Trim(),
_createParentId == 0 ? null : _createParentId, user,
folderId: FolderId);
folderId: FolderId));
if (result.IsSuccess)
{
@@ -2,6 +2,8 @@
@using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management
@inject IServiceProvider MutationServices
@page "/design/templates/{Id:int}"
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@@ -569,7 +571,7 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteTemplateAsync(_selectedTemplate.Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteTemplateAsync(_selectedTemplate.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Template '{_selectedTemplate.Name}' deleted.");
@@ -592,9 +594,9 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.UpdateTemplateAsync(
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateTemplateAsync(
_selectedTemplate.Id, _editName.Trim(), _editDescription?.Trim(),
_editParentId == 0 ? null : _editParentId, user);
_editParentId == 0 ? null : _editParentId, user));
if (result.IsSuccess)
{
@@ -818,7 +820,7 @@
IsInherited = attr.IsInherited,
LockedInDerived = newValue,
};
var result = await TemplateService.UpdateAttributeAsync(attr.Id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(attr.Id, proposed, user));
if (result.IsSuccess) { attr.LockedInDerived = newValue; _toast.ShowSuccess("Lock-in-derived updated."); }
else _toast.ShowError(result.Error);
}
@@ -841,7 +843,7 @@
IsInherited = false,
LockedInDerived = false,
};
var result = await TemplateService.UpdateAttributeAsync(attr.Id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(attr.Id, proposed, user));
if (result.IsSuccess) { _toast.ShowSuccess($"Override saved for '{attr.Name}'."); await LoadAsync(); }
else _toast.ShowError(result.Error);
}
@@ -864,7 +866,7 @@
IsInherited = true,
LockedInDerived = false,
};
var result = await TemplateService.UpdateAttributeAsync(attr.Id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(attr.Id, proposed, user));
if (result.IsSuccess) { _toast.ShowSuccess($"'{attr.Name}' reverted to base."); await LoadAsync(); }
else _toast.ShowError(result.Error);
}
@@ -882,7 +884,7 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.ResyncInheritedMembersAsync(Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.ResyncInheritedMembersAsync(Id, user));
if (result.IsSuccess)
{
var r = result.Value;
@@ -1284,7 +1286,7 @@
IsInherited = script.IsInherited,
LockedInDerived = newValue,
};
var result = await TemplateService.UpdateScriptAsync(script.Id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateScriptAsync(script.Id, proposed, user));
if (result.IsSuccess) { script.LockedInDerived = newValue; _toast.ShowSuccess("Lock-in-derived updated."); }
else _toast.ShowError(result.Error);
}
@@ -1308,7 +1310,7 @@
IsInherited = true,
LockedInDerived = false,
};
var result = await TemplateService.UpdateScriptAsync(script.Id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateScriptAsync(script.Id, proposed, user));
if (result.IsSuccess) { _toast.ShowSuccess($"Script '{script.Name}' reverted to base."); await LoadAsync(); }
else _toast.ShowError(result.Error);
}
@@ -1426,7 +1428,7 @@
IsInherited = existing.IsInherited,
LockedInDerived = existing.LockedInDerived,
};
var result = await TemplateService.UpdateAttributeAsync(id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(id, proposed, user));
if (!result.IsSuccess) return result.Error;
_toast.ShowSuccess($"Attribute '{existing.Name}' updated.");
@@ -1442,7 +1444,7 @@
DataSourceReference = draft.DataSourceRef?.Trim()
};
var addResult = await TemplateService.AddAttributeAsync(_selectedTemplate.Id, attr, user);
var addResult = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddAttributeAsync(_selectedTemplate.Id, attr, user));
if (!addResult.IsSuccess) return addResult.Error;
_toast.ShowSuccess($"Attribute '{draft.Name}' added.");
@@ -1454,7 +1456,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Attribute", $"Delete attribute '{attr.Name}'?", danger: true);
if (!confirmed) return;
var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteAttributeAsync(attr.Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteAttributeAsync(attr.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Attribute '{attr.Name}' deleted.");
@@ -1562,7 +1564,7 @@
Description = existing.Description,
OnTriggerScriptId = existing.OnTriggerScriptId,
};
var result = await TemplateService.UpdateAlarmAsync(id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAlarmAsync(id, proposed, user));
if (!result.IsSuccess) return result.Error;
_toast.ShowSuccess($"Alarm '{existing.Name}' updated.");
@@ -1578,7 +1580,7 @@
IsMesReportable = draft.IsMesReportable
};
var addResult = await TemplateService.AddAlarmAsync(_selectedTemplate.Id, alarm, user);
var addResult = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddAlarmAsync(_selectedTemplate.Id, alarm, user));
if (!addResult.IsSuccess) return addResult.Error;
_toast.ShowSuccess($"Alarm '{draft.Name}' added.");
@@ -1590,7 +1592,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Alarm", $"Delete alarm '{alarm.Name}'?", danger: true);
if (!confirmed) return;
var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteAlarmAsync(alarm.Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteAlarmAsync(alarm.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Alarm '{alarm.Name}' deleted.");
@@ -1698,7 +1700,7 @@
IsInherited = existing.IsInherited,
LockedInDerived = existing.LockedInDerived,
};
var result = await TemplateService.UpdateScriptAsync(id, proposed, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateScriptAsync(id, proposed, user));
if (!result.IsSuccess) return result.Error;
_toast.ShowSuccess($"Script '{existing.Name}' updated.");
@@ -1716,7 +1718,7 @@
ExecutionTimeoutSeconds = NormalizeExecutionTimeout(draft.ExecutionTimeoutSeconds)
};
var addResult = await TemplateService.AddScriptAsync(_selectedTemplate.Id, script, user);
var addResult = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddScriptAsync(_selectedTemplate.Id, script, user));
if (!addResult.IsSuccess) return addResult.Error;
_toast.ShowSuccess($"Script '{draft.Name}' added.");
@@ -1728,7 +1730,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Script", $"Delete script '{script.Name}'?", danger: true);
if (!confirmed) return;
var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteScriptAsync(script.Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteScriptAsync(script.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Script '{script.Name}' deleted.");
@@ -1,4 +1,7 @@
@page "/design/templates"
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -8,8 +11,6 @@
@using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject TemplateService TemplateService
@inject TemplateFolderService TemplateFolderService
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@inject IDialogService Dialog
@@ -355,7 +356,7 @@
if (string.IsNullOrWhiteSpace(name)) return;
var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.CreateFolderAsync(name.Trim(), parentFolderId, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.CreateFolderAsync(name.Trim(), parentFolderId, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Folder '{result.Value.Name}' created.");
@@ -378,7 +379,7 @@
if (result is null) return;
var user = await GetCurrentUserAsync();
var moved = await TemplateService.MoveTemplateAsync(templateId, result.NewFolderId, user);
var moved = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.MoveTemplateAsync(templateId, result.NewFolderId, user));
if (moved.IsSuccess)
{
_toast.ShowSuccess($"Template '{label}' moved.");
@@ -430,7 +431,7 @@
if (result is null) return;
var user = await GetCurrentUserAsync();
var moved = await TemplateFolderService.MoveFolderAsync(folderId, result.NewParentId, user);
var moved = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.MoveFolderAsync(folderId, result.NewParentId, user));
if (moved.IsSuccess)
{
_toast.ShowSuccess($"Folder '{label}' moved.");
@@ -451,7 +452,7 @@
private async Task ReorderFolder(int folderId, ReorderDirection direction)
{
var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.ReorderFolderAsync(folderId, direction, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.ReorderFolderAsync(folderId, direction, user));
if (result.IsSuccess)
{
await LoadTemplatesAsync();
@@ -542,7 +543,7 @@
if (string.IsNullOrWhiteSpace(newName)) return;
var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.RenameFolderAsync(folderId, newName, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.RenameFolderAsync(folderId, newName, user));
if (result.IsSuccess)
{
_toast.ShowSuccess("Folder renamed.");
@@ -560,7 +561,7 @@
if (!confirmed) return;
var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.DeleteFolderAsync(folderId, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.DeleteFolderAsync(folderId, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Folder '{label}' deleted.");
@@ -583,7 +584,7 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteTemplateAsync(template.Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteTemplateAsync(template.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Template '{template.Name}' deleted.");
@@ -616,7 +617,7 @@
if (result is null) return;
var user = await GetCurrentUserAsync();
var composed = await TemplateService.AddCompositionAsync(result.ParentTemplateId, sourceId, result.SlotName, user);
var composed = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddCompositionAsync(result.ParentTemplateId, sourceId, result.SlotName, user));
if (composed.IsSuccess)
{
_toast.ShowSuccess($"Composed '{sourceName}' as '{result.SlotName}'.");
@@ -649,7 +650,7 @@
if (string.IsNullOrWhiteSpace(newName) || newName.Trim() == composition.InstanceName) return;
var user = await GetCurrentUserAsync();
var result = await TemplateService.RenameCompositionAsync(composition.Id, newName.Trim(), user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.RenameCompositionAsync(composition.Id, newName.Trim(), user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Slot renamed to '{newName.Trim()}'.");
@@ -670,7 +671,7 @@
if (!confirmed) return;
var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteCompositionAsync(composition.Id, user);
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteCompositionAsync(composition.Id, user));
if (result.IsSuccess)
{
_toast.ShowSuccess($"Composition '{composition.InstanceName}' removed.");
@@ -3,7 +3,9 @@ using System.Text.Json;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
@@ -85,6 +87,7 @@ public partial class TransportImport : ComponentBase, IDisposable
[Inject] private IOptions<TransportOptions> Options { get; set; } = default!;
[Inject] private IAuditService AuditService { get; set; } = default!;
[Inject] private ScadaBridgeDbContext DbContext { get; set; } = default!;
[Inject] private IServiceScopeFactory ScopeFactory { get; set; } = default!;
// Register row 44: the per-IP-per-hour unlock throttle needs the caller's
// address, and HttpContext is long gone by the time a circuit submits a
@@ -870,12 +873,18 @@ public partial class TransportImport : ComponentBase, IDisposable
// central-config-only bundles (no required mappings) this is
// BundleNameMap.Empty, which the importer normalises away.
var nameMap = BuildNameMap();
_result = await BundleImporter.ApplyAsync(
_session.SessionId,
_resolutions.Values.ToList(),
// Apply loads and rewrites existing rows, so it runs on its own DI scope
// (code review 2026-12-02 UI-1): the circuit's context reads without tracking
// and must never carry a write. The session lives in the singleton store, so a
// fresh importer instance continues the same session.
var sessionId = _session.SessionId;
var resolutions = _resolutions.Values.ToList();
_result = await ScopeFactory.InNewScopeAsync((IBundleImporter importer) => importer.ApplyAsync(
sessionId,
resolutions,
user,
CancellationToken.None,
nameMap: nameMap);
nameMap: nameMap));
_step = ImportWizardStep.Result;
}
catch (SemanticValidationException ex)
@@ -1,6 +1,7 @@
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
@@ -38,6 +39,12 @@ public static class ServiceCollectionExtensions
// Resolves the current user's permitted site set from their SiteId claims
// so Deployment/Monitoring pages can enforce site scoping.
services.AddScoped<SiteScopeService>();
// Code review 2026-12-02 UI-1: the circuit-lifetime configuration DbContext reads
// without tracking, so a reload always sees changes made in other scopes. Mutating
// page actions run on their own scope (ConfigurationCommandService, the management
// actor, or ScopedServiceExtensions.InNewScopeAsync), never on the circuit's context.
services.TryAddEnumerable(ServiceDescriptor.Scoped<
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHandler, CircuitDbContextTrackingHandler>());
services.AddScoped<AuthorizedManualFailoverService>();
services.AddScoped<ConfigurationCommandService>();
@@ -0,0 +1,56 @@
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
/// <summary>
/// Gives each Blazor Server circuit's <see cref="ScadaBridgeDbContext"/> a no-tracking query
/// default (code review 2026-12-02, UI-1).
/// </summary>
/// <remarks>
/// <para>
/// The configuration <see cref="ScadaBridgeDbContext"/> is registered scoped, and in Blazor
/// Server one DI scope lives for the whole circuit — hours, across page navigations. With EF's
/// default tracking behaviour every entity a page ever loaded stayed in that context's change
/// tracker, and a later tracking query for the same key returned the first-loaded instance
/// without refreshing its values. Changes made in any other scope (the management actor, another
/// user, the CLI, a Transport import) were therefore never seen by the circuit: a moved data
/// connection stayed under its old site, a renamed area kept its old name on the live Topology,
/// and a template script re-opened after a CLI edit showed — and on save wrote back — the old body.
/// </para>
/// <para>
/// Only the circuit's context is switched; contexts in every other scope (management-actor
/// commands, the configuration command transaction, HTTP request scopes, hosted services,
/// singleton actors) keep EF's tracking default, so the shared services that load-modify-save
/// still work there. Page actions that mutate configuration never run on the circuit's context:
/// they go through <c>ConfigurationCommandService</c> (its own transaction scope), the
/// <c>ManagementActor</c>, or <see cref="ScopedServiceExtensions.InNewScopeAsync{TService, TResult}"/>.
/// </para>
/// <para>
/// The switch is made in the constructor: the circuit factory resolves every
/// <see cref="CircuitHandler"/> from the new circuit's scope while it builds the circuit host,
/// before any component is created, so no page query can run on the context first. The context is
/// resolved optionally because hosts without the configuration database (tests, a non-central
/// role) have none.
/// </para>
/// </remarks>
public sealed class CircuitDbContextTrackingHandler : CircuitHandler
{
/// <summary>The query-tracking behaviour every circuit's configuration context runs with.</summary>
public const QueryTrackingBehavior CircuitQueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
/// <summary>Switches the circuit scope's configuration context to the no-tracking default.</summary>
/// <param name="circuitServices">The circuit's scoped service provider.</param>
public CircuitDbContextTrackingHandler(IServiceProvider circuitServices)
{
ArgumentNullException.ThrowIfNull(circuitServices);
var context = circuitServices.GetService<ScadaBridgeDbContext>();
if (context is not null)
context.ChangeTracker.QueryTrackingBehavior = CircuitQueryTrackingBehavior;
}
/// <summary>Runs ahead of other handlers so nothing observes the context first.</summary>
public override int Order => int.MinValue;
}
@@ -15,7 +15,7 @@ namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
/// </para>
/// <para>
/// The circuit's own context runs with a no-tracking default
/// (<c>CircuitDbContextTrackingHandler</c>), so a load-modify-save service run on it would
/// (<see cref="CircuitDbContextTrackingHandler"/>), so a load-modify-save service run on it would
/// silently persist nothing. A fresh scope gets an ordinary tracking context that starts empty,
/// so the service always reads the current row and its write lands; the scope is disposed when
/// the action ends, so nothing stale is left behind for the next action, and the action does