refactor(ioc): 为依赖注入容器注册方法添加线程安全锁

- 在RegisterSingleton方法中添加读写锁保护
- 在RegisterFactory方法中添加读写锁保护
- 在ExecuteServicesHook方法中添加读写锁保护
- 确保在冻结状态下抛出异常
- 添加日志记录单例注册操作
- 统一异常处理和资源清理逻辑
This commit is contained in:
GeWuYou 2026-02-14 19:28:24 +08:00 committed by gewuyou
parent ae8ad29806
commit a420a41a55

View File

@ -104,11 +104,23 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
/// <typeparam name="TService">服务接口或基类类型</typeparam>
/// <typeparam name="TImpl">具体的实现类型</typeparam>
public void RegisterSingleton<TService, TImpl>()
where TImpl : class, TService where TService : class
where TImpl : class, TService
where TService : class
{
Services.AddSingleton<TService, TImpl>();
_lock.EnterWriteLock();
try
{
ThrowIfFrozen();
Services.AddSingleton<TService, TImpl>();
_logger.Debug($"Singleton registered: {typeof(TService).Name}");
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// 注册多个实例到其所有接口和具体类型
/// 实现一个实例支持多种接口类型的解析
@ -234,12 +246,22 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
/// </summary>
/// <typeparam name="TService">服务类型</typeparam>
/// <param name="factory">创建服务实例的工厂委托函数接收IServiceProvider参数</param>
public void RegisterFactory<TService>(Func<IServiceProvider, TService> factory) where TService : class
public void RegisterFactory<TService>(
Func<IServiceProvider, TService> factory) where TService : class
{
ThrowIfFrozen();
Services.AddSingleton(factory);
_lock.EnterWriteLock();
try
{
ThrowIfFrozen();
Services.AddSingleton(factory);
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// 注册中介行为管道
/// 用于配置Mediator框架的行为拦截和处理逻辑
@ -269,9 +291,18 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
/// 配置服务
/// </summary>
/// <param name="configurator">服务配置委托</param>
public void ExecuteServicesHook(Action<IServiceCollection>? configurator = null)
public void ExecuteServicesHook(Action<IServiceCollection>? configurator)
{
configurator?.Invoke(Services);
_lock.EnterWriteLock();
try
{
ThrowIfFrozen();
configurator?.Invoke(Services);
}
finally
{
_lock.ExitWriteLock();
}
}
#endregion