TekH fbf9488c55 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.
2025-10-23 09:53:50 +02:00

115 lines
3.0 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using System.Collections;
#if NETFRAMEWORK
using System;
using System.Collections.Generic;
#endif
namespace DigitalData.Core.Abstractions
{
public class Factory : IServiceProvider, IServiceCollection
{
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();
_lazyServiceProvider = new Lazy<IServiceProvider>(() => _serviceCollection.BuildServiceProvider());
}
#region Service Provider
public object
#if NET
?
#endif
GetService(Type serviceType)
{
return _lazyServiceProvider.Value.GetService(serviceType);
}
#endregion
#region Service Collection
public int Count => _serviceCollection.Count;
public bool IsReadOnly => _serviceCollection.IsReadOnly;
public ServiceDescriptor this[int index]
{
get => _serviceCollection[index];
set
{
EnsureNotBuilt();
_serviceCollection[index] = value;
}
}
public int IndexOf(ServiceDescriptor item)
{
return _serviceCollection.IndexOf(item);
}
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();
}
public bool Contains(ServiceDescriptor item)
{
return _serviceCollection.Contains(item);
}
public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
{
_serviceCollection.CopyTo(array, arrayIndex);
}
public bool Remove(ServiceDescriptor item)
{
EnsureNotBuilt();
return _serviceCollection.Remove(item);
}
public IEnumerator<ServiceDescriptor> GetEnumerator()
{
return _serviceCollection.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
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
}
}