A:添加新模块
This commit is contained in:
1 parent
43ff9bc57f
commit
25c4a663a5
9 files changed
+418
-15
No files matched your search
@@ -1,7 +0,0 @@
|
||||
namespace Common
|
||||
{
|
||||
public class Class1
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
namespace Common;
|
||||
|
||||
/// <summary>
|
||||
/// Global 轻量级 DI 容器使用示例
|
||||
/// </summary>
|
||||
public static class GlobalUsageExamples
|
||||
{
|
||||
/// <summary>
|
||||
/// 基础使用示例
|
||||
/// </summary>
|
||||
public static void BasicUsageExamples()
|
||||
{
|
||||
// 1. 注册和获取单例服务
|
||||
var config = new AppConfig { AppName = "MyApp", Version = "1.0" };
|
||||
Global.RegisterSingleton(config);
|
||||
|
||||
var retrievedConfig = Global.Get<AppConfig>();
|
||||
Console.WriteLine($"App: {retrievedConfig.AppName} v{retrievedConfig.Version}");
|
||||
|
||||
// 2. 使用工厂方法注册单例
|
||||
Global.RegisterSingleton(() => new DatabaseConnection("connection-string"));
|
||||
var db = Global.Get<DatabaseConnection>();
|
||||
|
||||
// 3. 注册瞬态服务(每次获取都是新实例)
|
||||
Global.RegisterTransient(() => new RequestContext
|
||||
{
|
||||
RequestId = Guid.NewGuid().ToString(),
|
||||
Timestamp = DateTime.Now
|
||||
});
|
||||
|
||||
var request1 = Global.Get<RequestContext>();
|
||||
var request2 = Global.Get<RequestContext>();
|
||||
// request1 和 request2 是不同的实例
|
||||
|
||||
// 4. 尝试获取服务
|
||||
if (Global.TryGet<ILogger>(out var logger))
|
||||
{
|
||||
logger.Log("Service found");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Logger not registered");
|
||||
}
|
||||
|
||||
// 5. 获取服务或默认值
|
||||
var fallbackLogger = Global.GetOrDefault<ILogger>(new ConsoleLogger());
|
||||
|
||||
// 6. 检查服务是否注册
|
||||
if (Global.IsRegistered<AppConfig>())
|
||||
{
|
||||
Console.WriteLine("AppConfig is registered");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务变更通知示例
|
||||
/// </summary>
|
||||
public static void ChangeNotificationExamples()
|
||||
{
|
||||
// 1. 订阅服务变更通知
|
||||
Global.Subscribe<AppConfig>(eventArgs =>
|
||||
{
|
||||
Console.WriteLine($"Config changed at {eventArgs.ChangedAt}");
|
||||
Console.WriteLine($"Old: {eventArgs.OldValue?.AppName ?? "null"}");
|
||||
Console.WriteLine($"New: {eventArgs.NewValue.AppName}");
|
||||
});
|
||||
|
||||
// 2. 注册初始配置
|
||||
var config = new AppConfig { AppName = "MyApp", Version = "1.0" };
|
||||
Global.RegisterSingleton(config);
|
||||
|
||||
// 3. 更新配置(会触发通知)
|
||||
var newConfig = new AppConfig { AppName = "MyApp", Version = "2.0" };
|
||||
Global.Update(newConfig);
|
||||
|
||||
// 4. 也可以在注册时就设置为通知模式
|
||||
var anotherConfig = new AppConfig { AppName = "MyApp", Version = "3.0" };
|
||||
Global.RegisterSingleton(anotherConfig, notifyIfExists: true); // 会触发通知
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 实时配置更新示例
|
||||
/// </summary>
|
||||
public static void LiveConfigurationExample()
|
||||
{
|
||||
// 场景:应用程序配置可以动态更新,所有组件都能收到通知
|
||||
|
||||
// 1. 定义配置变更处理器
|
||||
void OnConfigChanged(ServiceChangedEventArgs<AppConfig> e)
|
||||
{
|
||||
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Configuration updated:");
|
||||
Console.WriteLine($" Old Version: {e.OldValue?.Version}");
|
||||
Console.WriteLine($" New Version: {e.NewValue.Version}");
|
||||
|
||||
// 在这里可以执行配置变更后的操作
|
||||
// 例如:重新连接数据库、刷新缓存等
|
||||
}
|
||||
|
||||
// 2. 订阅配置变更
|
||||
Global.Subscribe<AppConfig>(OnConfigChanged);
|
||||
|
||||
// 3. 注册初始配置
|
||||
Global.RegisterSingleton(new AppConfig { AppName = "MyApp", Version = "1.0" });
|
||||
|
||||
// 4. 模拟配置文件被修改,更新配置
|
||||
Thread.Sleep(1000);
|
||||
Global.Update(new AppConfig { AppName = "MyApp", Version = "1.1" });
|
||||
|
||||
Thread.Sleep(1000);
|
||||
Global.Update(new AppConfig { AppName = "MyApp", Version = "1.2" });
|
||||
|
||||
// 5. 取消订阅
|
||||
Global.Unsubscribe<AppConfig>(OnConfigChanged);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 多订阅者示例
|
||||
/// </summary>
|
||||
public static void MultipleSubscribersExample()
|
||||
{
|
||||
// 场景:多个组件都关心某个服务的变更
|
||||
|
||||
// 订阅者 1:UI 组件
|
||||
Global.Subscribe<UserSession>(e =>
|
||||
{
|
||||
Console.WriteLine($"[UI] User session updated: {e.NewValue.Username}");
|
||||
// 更新UI显示
|
||||
});
|
||||
|
||||
// 订阅者 2:日志组件
|
||||
Global.Subscribe<UserSession>(e =>
|
||||
{
|
||||
Console.WriteLine($"[LOG] Session change detected at {e.ChangedAt}");
|
||||
// 记录日志
|
||||
});
|
||||
|
||||
// 订阅者 3:分析组件
|
||||
Global.Subscribe<UserSession>(e =>
|
||||
{
|
||||
Console.WriteLine($"[ANALYTICS] Tracking user: {e.NewValue.Username}");
|
||||
// 发送分析数据
|
||||
});
|
||||
|
||||
// 注册会话
|
||||
Global.RegisterSingleton(new UserSession { Username = "user1", LoginTime = DateTime.Now });
|
||||
|
||||
// 更新会话(所有订阅者都会收到通知)
|
||||
Thread.Sleep(100);
|
||||
Global.Update(new UserSession { Username = "user2", LoginTime = DateTime.Now });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务生命周期对比示例
|
||||
/// </summary>
|
||||
public static void LifetimeComparisonExample()
|
||||
{
|
||||
// 1. 单例服务:整个应用生命周期内只有一个实例
|
||||
Global.RegisterSingleton(() => new CacheService());
|
||||
var cache1 = Global.Get<CacheService>();
|
||||
var cache2 = Global.Get<CacheService>();
|
||||
Console.WriteLine($"Singleton: {ReferenceEquals(cache1, cache2)}"); // True
|
||||
|
||||
// 2. 瞬态服务:每次获取都是新实例
|
||||
Global.RegisterTransient(() => new OperationContext());
|
||||
var ctx1 = Global.Get<OperationContext>();
|
||||
var ctx2 = Global.Get<OperationContext>();
|
||||
Console.WriteLine($"Transient: {ReferenceEquals(ctx1, ctx2)}"); // False
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务管理示例
|
||||
/// </summary>
|
||||
public static void ServiceManagementExample()
|
||||
{
|
||||
// 注册多个服务
|
||||
Global.RegisterSingleton(new AppConfig { AppName = "MyApp" });
|
||||
Global.RegisterSingleton(() => new DatabaseConnection("conn-string"));
|
||||
Global.RegisterTransient(() => new RequestContext());
|
||||
|
||||
// 查看已注册服务数量
|
||||
Console.WriteLine($"Total services: {Global.Count}");
|
||||
|
||||
// 注销特定服务
|
||||
if (Global.Unregister<RequestContext>())
|
||||
{
|
||||
Console.WriteLine("RequestContext unregistered");
|
||||
}
|
||||
|
||||
// 清除所有服务
|
||||
Global.Clear();
|
||||
Console.WriteLine($"Services after clear: {Global.Count}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 错误处理示例
|
||||
/// </summary>
|
||||
public static void ErrorHandlingExample()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 尝试获取未注册的服务
|
||||
var service = Global.Get<ILogger>();
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
Console.WriteLine($"Error: {ex.Message}");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// 尝试更新瞬态服务
|
||||
Global.RegisterTransient(() => new RequestContext());
|
||||
Global.Update(new RequestContext()); // 会抛出异常
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
Console.WriteLine($"Error: {ex.Message}");
|
||||
}
|
||||
|
||||
// 安全的获取方式
|
||||
if (Global.TryGet<ILogger>(out var logger))
|
||||
{
|
||||
logger.Log("Success");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Logger not available, using fallback");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 工厂模式集成示例
|
||||
/// </summary>
|
||||
public static void FactoryPatternExample()
|
||||
{
|
||||
// 使用工厂方法创建复杂对象
|
||||
Global.RegisterSingleton(() =>
|
||||
{
|
||||
var config = LoadConfigFromFile();
|
||||
ValidateConfig(config);
|
||||
return config;
|
||||
});
|
||||
|
||||
// 延迟初始化:只有在第一次 Get 时才会调用工厂方法
|
||||
var config = Global.Get<AppConfig>(); // 此时才执行工厂方法
|
||||
|
||||
// 后续获取都返回同一个实例
|
||||
var sameConfig = Global.Get<AppConfig>(); // 直接返回,不再调用工厂
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 线程安全示例
|
||||
/// </summary>
|
||||
public static void ThreadSafetyExample()
|
||||
{
|
||||
// 注册服务
|
||||
Global.RegisterSingleton(() =>
|
||||
{
|
||||
Thread.Sleep(100); // 模拟复杂的初始化过程
|
||||
return new CacheService();
|
||||
});
|
||||
|
||||
// 多线程并发获取(保证只创建一次)
|
||||
var tasks = Enumerable.Range(0, 10).Select(i =>
|
||||
Task.Run(() =>
|
||||
{
|
||||
var service = Global.Get<CacheService>();
|
||||
Console.WriteLine($"Thread {i}: {service.GetHashCode()}");
|
||||
})
|
||||
);
|
||||
|
||||
Task.WaitAll(tasks.ToArray());
|
||||
// 所有线程获取的都是同一个实例
|
||||
}
|
||||
|
||||
#region 辅助类型
|
||||
|
||||
private class AppConfig
|
||||
{
|
||||
public string AppName { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
}
|
||||
|
||||
private class DatabaseConnection
|
||||
{
|
||||
public string ConnectionString { get; }
|
||||
public DatabaseConnection(string connectionString)
|
||||
{
|
||||
ConnectionString = connectionString;
|
||||
}
|
||||
}
|
||||
|
||||
private class RequestContext
|
||||
{
|
||||
public string RequestId { get; set; } = Guid.NewGuid().ToString();
|
||||
public DateTime Timestamp { get; set; } = DateTime.Now;
|
||||
}
|
||||
|
||||
private interface ILogger
|
||||
{
|
||||
void Log(string message);
|
||||
}
|
||||
|
||||
private class ConsoleLogger : ILogger
|
||||
{
|
||||
public void Log(string message) => Console.WriteLine($"[LOG] {message}");
|
||||
}
|
||||
|
||||
private class UserSession
|
||||
{
|
||||
public string Username { get; set; } = "";
|
||||
public DateTime LoginTime { get; set; }
|
||||
}
|
||||
|
||||
private class CacheService
|
||||
{
|
||||
private readonly Dictionary<string, object> _cache = new();
|
||||
}
|
||||
|
||||
private class OperationContext
|
||||
{
|
||||
public Guid OperationId { get; } = Guid.NewGuid();
|
||||
}
|
||||
|
||||
private static AppConfig LoadConfigFromFile()
|
||||
{
|
||||
// 模拟从文件加载配置
|
||||
return new AppConfig { AppName = "MyApp", Version = "1.0" };
|
||||
}
|
||||
|
||||
private static void ValidateConfig(AppConfig config)
|
||||
{
|
||||
if (string.IsNullOrEmpty(config.AppName))
|
||||
throw new InvalidOperationException("AppName cannot be empty");
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
Reference in new issue
Block a user