From a420a41a55a281bc3d403bc7a155bea752d3658f Mon Sep 17 00:00:00 2001
From: GeWuYou <95328647+GeWuYou@users.noreply.github.com>
Date: Sat, 14 Feb 2026 19:28:24 +0800
Subject: [PATCH] =?UTF-8?q?refactor(ioc):=20=E4=B8=BA=E4=BE=9D=E8=B5=96?=
=?UTF-8?q?=E6=B3=A8=E5=85=A5=E5=AE=B9=E5=99=A8=E6=B3=A8=E5=86=8C=E6=96=B9?=
=?UTF-8?q?=E6=B3=95=E6=B7=BB=E5=8A=A0=E7=BA=BF=E7=A8=8B=E5=AE=89=E5=85=A8?=
=?UTF-8?q?=E9=94=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 在RegisterSingleton方法中添加读写锁保护
- 在RegisterFactory方法中添加读写锁保护
- 在ExecuteServicesHook方法中添加读写锁保护
- 确保在冻结状态下抛出异常
- 添加日志记录单例注册操作
- 统一异常处理和资源清理逻辑
---
GFramework.Core/ioc/MicrosoftDiContainer.cs | 45 +++++++++++++++++----
1 file changed, 38 insertions(+), 7 deletions(-)
diff --git a/GFramework.Core/ioc/MicrosoftDiContainer.cs b/GFramework.Core/ioc/MicrosoftDiContainer.cs
index b1a0093..d588f6f 100644
--- a/GFramework.Core/ioc/MicrosoftDiContainer.cs
+++ b/GFramework.Core/ioc/MicrosoftDiContainer.cs
@@ -104,11 +104,23 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
/// 服务接口或基类类型
/// 具体的实现类型
public void RegisterSingleton()
- where TImpl : class, TService where TService : class
+ where TImpl : class, TService
+ where TService : class
{
- Services.AddSingleton();
+ _lock.EnterWriteLock();
+ try
+ {
+ ThrowIfFrozen();
+ Services.AddSingleton();
+ _logger.Debug($"Singleton registered: {typeof(TService).Name}");
+ }
+ finally
+ {
+ _lock.ExitWriteLock();
+ }
}
+
///
/// 注册多个实例到其所有接口和具体类型
/// 实现一个实例支持多种接口类型的解析
@@ -234,12 +246,22 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
///
/// 服务类型
/// 创建服务实例的工厂委托函数,接收IServiceProvider参数
- public void RegisterFactory(Func factory) where TService : class
+ public void RegisterFactory(
+ Func factory) where TService : class
{
- ThrowIfFrozen();
- Services.AddSingleton(factory);
+ _lock.EnterWriteLock();
+ try
+ {
+ ThrowIfFrozen();
+ Services.AddSingleton(factory);
+ }
+ finally
+ {
+ _lock.ExitWriteLock();
+ }
}
+
///
/// 注册中介行为管道
/// 用于配置Mediator框架的行为拦截和处理逻辑
@@ -269,9 +291,18 @@ public class MicrosoftDiContainer(IServiceCollection? serviceCollection = null)
/// 配置服务
///
/// 服务配置委托
- public void ExecuteServicesHook(Action? configurator = null)
+ public void ExecuteServicesHook(Action? configurator)
{
- configurator?.Invoke(Services);
+ _lock.EnterWriteLock();
+ try
+ {
+ ThrowIfFrozen();
+ configurator?.Invoke(Services);
+ }
+ finally
+ {
+ _lock.ExitWriteLock();
+ }
}
#endregion