From 50a056d1109632df18b3108e5cbbb8a8ff541814 Mon Sep 17 00:00:00 2001 From: TekH Date: Wed, 29 Oct 2025 15:57:36 +0100 Subject: [PATCH] feat(Factory): add PostBuildBehavior to control post-build modification behavior in Factory Introduced PostBuildBehavior enum and BehaveOnPostBuild() method to configure behavior when modifying the service collection after the service provider is built. Replaced EnsureNotBuilt() with EnsureBuilt() to support configurable handling (throw exception or ignore). This improves flexibility in scenarios where post-build service modifications should be optionally allowed or silently ignored. --- DigitalData.Core.Abstractions/Factory.cs | 42 +++++++++++++++++++----- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/DigitalData.Core.Abstractions/Factory.cs b/DigitalData.Core.Abstractions/Factory.cs index 7ac6771..f9d2921 100644 --- a/DigitalData.Core.Abstractions/Factory.cs +++ b/DigitalData.Core.Abstractions/Factory.cs @@ -16,6 +16,14 @@ namespace DigitalData.Core.Abstractions private bool IsBuilt => _lazyServiceProvider.IsValueCreated; + private PostBuildBehavior _pbBehavior = PostBuildBehavior.ThrowException; + + public Factory BehaveOnPostBuild(PostBuildBehavior postBuildBehavior) + { + _pbBehavior = postBuildBehavior; + return this; + } + public Factory() { _lazyServiceProvider = new Lazy(() => _serviceCollection.BuildServiceProvider()); @@ -42,7 +50,8 @@ namespace DigitalData.Core.Abstractions get => _serviceCollection[index]; set { - EnsureNotBuilt(); + if (EnsureBuilt()) + return; _serviceCollection[index] = value; } } @@ -54,25 +63,29 @@ namespace DigitalData.Core.Abstractions public void Insert(int index, ServiceDescriptor item) { - EnsureNotBuilt(); + if (EnsureBuilt()) + return; _serviceCollection.Insert(index, item); } public void RemoveAt(int index) { - EnsureNotBuilt(); + if (EnsureBuilt()) + return; _serviceCollection.RemoveAt(index); } public void Add(ServiceDescriptor item) { - EnsureNotBuilt(); + if (EnsureBuilt()) + return; _serviceCollection.Add(item); } public void Clear() { - EnsureNotBuilt(); + if (EnsureBuilt()) + return; _serviceCollection.Clear(); } @@ -88,7 +101,8 @@ namespace DigitalData.Core.Abstractions public bool Remove(ServiceDescriptor item) { - EnsureNotBuilt(); + if (EnsureBuilt()) + return false; return _serviceCollection.Remove(item); } @@ -104,11 +118,23 @@ namespace DigitalData.Core.Abstractions #endregion #region Helpers - private void EnsureNotBuilt() + private bool EnsureBuilt() { if (IsBuilt) - throw new InvalidOperationException("Service provider has already been built. No further service modifications are allowed."); + { + return _pbBehavior == PostBuildBehavior.ThrowException + ? throw new InvalidOperationException("Service provider has already been built. No further service modifications are allowed.") + : true; + } + else + return false; } #endregion } + + public enum PostBuildBehavior + { + ThrowException, + Ignore + } } \ No newline at end of file