From fbf9488c5504345146ce6ca945a8da5e95ec8b33 Mon Sep 17 00:00:00 2001 From: TekH Date: Thu, 23 Oct 2025 09:53:50 +0200 Subject: [PATCH] feat(Factory): prevent service modifications after provider is built Added an `IsBuilt` property and `EnsureNotBuilt()` helper to `Factory` class to restrict modifications to the service collection once the service provider has been built. This ensures immutability and prevents runtime inconsistencies after initialization. --- DigitalData.Core.Abstractions/Factory.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/DigitalData.Core.Abstractions/Factory.cs b/DigitalData.Core.Abstractions/Factory.cs index 6a2c9a9..e42bc15 100644 --- a/DigitalData.Core.Abstractions/Factory.cs +++ b/DigitalData.Core.Abstractions/Factory.cs @@ -12,9 +12,10 @@ namespace DigitalData.Core.Abstractions public static readonly Factory Instance = new Factory(); private readonly IServiceCollection _serviceCollection = new ServiceCollection(); - private readonly Lazy _lazyServiceProvider; + private bool IsBuilt => _lazyServiceProvider.IsValueCreated; + public Factory() { _serviceCollection = new ServiceCollection(); @@ -40,7 +41,11 @@ namespace DigitalData.Core.Abstractions public ServiceDescriptor this[int index] { get => _serviceCollection[index]; - set => _serviceCollection[index] = value; + set + { + EnsureNotBuilt(); + _serviceCollection[index] = value; + } } public int IndexOf(ServiceDescriptor item) @@ -50,21 +55,25 @@ namespace DigitalData.Core.Abstractions public void Insert(int index, ServiceDescriptor item) { + EnsureNotBuilt(); _serviceCollection.Insert(index, item); } public void RemoveAt(int index) { + EnsureNotBuilt(); _serviceCollection.RemoveAt(index); } public void Add(ServiceDescriptor item) { + EnsureNotBuilt(); _serviceCollection.Add(item); } public void Clear() { + EnsureNotBuilt(); _serviceCollection.Clear(); } @@ -80,6 +89,7 @@ namespace DigitalData.Core.Abstractions public bool Remove(ServiceDescriptor item) { + EnsureNotBuilt(); return _serviceCollection.Remove(item); } @@ -93,5 +103,13 @@ namespace DigitalData.Core.Abstractions return (_serviceCollection as IEnumerable).GetEnumerator(); } #endregion + + #region Helpers + private void EnsureNotBuilt() + { + if (IsBuilt) + throw new InvalidOperationException("Service provider has already been built. No further service modifications are allowed."); + } + #endregion } } \ No newline at end of file