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.
This commit is contained in:
parent
ddbb70081e
commit
fbf9488c55
@ -12,9 +12,10 @@ namespace DigitalData.Core.Abstractions
|
||||
public static readonly Factory Instance = new Factory();
|
||||
|
||||
private readonly IServiceCollection _serviceCollection = new ServiceCollection();
|
||||
|
||||
private readonly Lazy<IServiceProvider> _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
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user