EventHub, Services, Dashboard, BusLibrary02, Static, Keys, Registration
D:\Projects\VS\WebService\WebService.slnx
D:\Projects\VS\WebService\EventHubRazorExample05\EventHubRazorExample05.csproj
D:/AAA/EventHubRazorExample05.txt
Two Services write LOGS to Separate BackgroundService
---------------------------------------------------------------------
// Program.cs
using EventHubRazorExample;
using BusLibrary02.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Reflection;
using EventHubRazorExample.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Настройка логгирования
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.SetMinimumLevel(
builder.Environment.IsDevelopment()
? LogLevel.Debug
: LogLevel.Information
);
// Добавляем Razor Pages
builder.Services.AddRazorPages();
// Регистрируем EventHub с динамическими подписками
builder.Services.AddEventHub(options =>
{
options.ChannelCapacity = 2048;
options.Assemblies = new[] { typeof(Program).Assembly };
});
// Регистрируем фоновые сервисы
builder.Services.AddHostedService<FirstBackgroundService>();
builder.Services.AddHostedService<SecondBackgroundService>();
builder.Services.AddHostedService<LoggerBackgroundService>();
builder.Services.Configure<ServicesConfiguration>(
builder.Configuration.GetSection("Services"));
var app = builder.Build();
// Автоматическая регистрация статических ключей для всех сообщений
using (var scope = app.Services.CreateScope())
{
try
{
var subscriptionManager = scope.ServiceProvider.GetRequiredService<IDynamicSubscriptionManager>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
// Регистрируем все типы сообщений из текущей сборки
var messageTypes = typeof(Program).Assembly.GetTypes()
.Where(t => typeof(IMessage).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface)
.Where(t => t.GetCustomAttribute<MessageKeyAttribute>() != null);
foreach (var type in messageTypes)
{
try
{
var attr = type.GetCustomAttribute<MessageKeyAttribute>();
if (attr != null)
{
// Используем рефлексию для вызова RegisterStaticKey<T>
var method = typeof(DynamicSubscriptionManager).GetMethod("RegisterStaticKey");
var genericMethod = method!.MakeGenericMethod(type);
genericMethod.Invoke(subscriptionManager, new object[] { attr.Key });
logger.LogDebug("Registered static key '{Key}' for message type {Type}",
attr.Key, type.Name);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error registering static key for type {Type}", type.Name);
}
}
logger.LogInformation("Registered {Count} message types with static keys", messageTypes.Count());
}
catch (Exception ex)
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Error during static key registration");
}
}
// Настройка конвейера
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
// Запускаем
Console.WriteLine();
Console.WriteLine("🚀 EventHub Razor Example Starting...");
Console.WriteLine("📡 Open browser to: https://localhost:5001");
Console.WriteLine("👀 Check console for service logs");
Console.WriteLine();
app.Run();
Комментариев нет:
Отправить комментарий