using Autofac; using MAX.Core.Infrastructure; using MAX.Notification; var builder = new ContainerBuilder(); new MAX.Core.Startup().Register(builder); builder.RegisterType().InstancePerLifetimeScope(); using var container = builder.Build(); using (var scope = container.BeginLifetimeScope()) { var publisher = scope.Resolve(); var manager = scope.Resolve(); Check(ReferenceEquals(publisher, manager), "发布接口和管理器应为同一实例"); var state = scope.Resolve(); await publisher.Publish(new Changed()); Check(state.Calls == 1, "程序集扫描和作用域内处理器解析"); var dynamicHandler = new DynamicHandler(); manager.RegisterNotification(dynamicHandler); await publisher.Publish(new Changed()); Check(state.Calls == 2 && dynamicHandler.Calls == 1, "容器和动态处理器均收到通知"); using var otherScope = container.BeginLifetimeScope(); var otherPublisher = otherScope.Resolve(); Check(!ReferenceEquals(publisher, otherPublisher), "不同作用域拥有不同发布器"); await otherPublisher.Publish(new Changed()); Check(otherScope.Resolve().Calls == 1 && state.Calls == 2, "处理器使用所属作用域的依赖"); Check(dynamicHandler.Calls == 1, "动态注册不泄漏到其他作用域"); } Console.WriteLine("MAX.Core notification integration tests passed."); static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } public sealed record Changed : INotification; public sealed class ScopeState { public int Calls { get; set; } } public sealed class ScopedHandler(ScopeState state) : INotificationHandler { public Task Handle(Changed notification, CancellationToken cancellationToken) { state.Calls++; return Task.CompletedTask; } } // 保持开放泛型,避免被程序集扫描为封闭处理器;由测试显式注册实例。 public class DynamicHandler : INotificationHandler where T : INotification { public int Calls { get; private set; } public Task Handle(T notification, CancellationToken cancellationToken) { Calls++; return Task.CompletedTask; } }