using Autofac; using Autofac.Extensions.DependencyInjection; using Common.Request; using Common.WX; using JWTHelper; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using MongoRepository.Config; using NLog.Extensions.Logging; using NLog.Web; using RedisHelper; using RedisService; using ScheduledService; using SharpAbp.Infrastructure.Api.Middleware; using StackExchange.Redis; using System.Text.Json; using UserApi; // <-- assembly marker using UserHost.Extension; using UserHost.Middleware; using UserService; using UserService.Hubs; using UserService.Jobs; Environment.SetEnvironmentVariable("SERVICE_NAME", Environment.GetEnvironmentVariable("SERVICE_NAME") ?? System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name ?? "UserHost"); Environment.SetEnvironmentVariable("INSTANCE_ID", Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "default"); var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers() .AddApplicationPart(typeof(AssemblyMarker).Assembly) .AddControllersAsServices(); builder.Logging.AddNLog(); builder.Host.UseNLog(); builder.Services.AddControllers().AddNewtonsoftJson( option => option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss" ); builder.Configuration.AddJsonFile(Path.Combine("Config", "system.json"), optional: true); builder.Services.Configure(builder.Configuration.GetSection(nameof(MongoDbSettings))); builder.Services.AddSingleton(sp => sp.GetRequiredService>().Value); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddAutoMapper(typeof(AutoMapperConfig)); builder.Services.AddScoped(); builder.Services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy(), tags: new[] { "self" }); builder.Services.AddSignalR(hubOptions => { hubOptions.MaximumReceiveMessageSize = 64 * 1024; // 64KB hubOptions.StreamBufferCapacity = 512; // hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(70); hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15); }).AddJsonProtocol() .AddStackExchangeRedis(builder.Configuration["RedisConfig:ConnectionString"], options => { options.Configuration.ChannelPrefix = RedisChannel.Literal("GameHub"); }); #region builder.Services.AddCors(options => { options.AddPolicy("Cors", policy => { policy .SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); #endregion #region jwt builder.Services.AddCustomJwt(builder.Configuration); #endregion #region redis builder.Services.AddRedisCache(builder.Configuration); #endregion #region Cap builder.Services.AddCap(builder.Configuration); #endregion builder.Services.AddCronJob(c => { c.TimeZoneInfo = TimeZoneInfo.Local; c.CronExpression = @"0 0 0 * * *"; }); builder.Services.AddCronJob(c => { c.TimeZoneInfo = TimeZoneInfo.Local; c.CronExpression = @"0 0 0 * * *"; }); // Autofac #region Swagger builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "UserApi", Description = "游戏大厅接口管理", Version = "v1" }); foreach (var xml in System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.xml")) { try { c.IncludeXmlComments(xml, true); } catch { } } }); #endregion builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer(builder => { builder.RegisterModule(); }); var app = builder.Build(); // if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region Swagger app.UseSwagger(c => c.RouteTemplate = "swagger/{documentName}/swagger.json"); app.UseSwaggerUI(c => { c.RoutePrefix = "swagger"; c.SwaggerEndpoint("v1/swagger.json", "UserApi v1"); }); #endregion app.UseCors("Cors"); app.UseRouting(); app.MapHub("/loginhub", options => { options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets; }); app.UseAuthentication(); app.UseAuthorization(); app.UseApiLogging(); app.MapControllers(); app.UseGlobalExceptionHandler(); app.MapHealthChecks("/health", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = async (context, report) => { context.Response.ContentType = "application/json"; var result = new { status = report.Status.ToString(), checks = report.Entries.Select(e => new { name = e.Key, status = e.Value.Status.ToString(), description = e.Value.Description, duration = e.Value.Duration.TotalMilliseconds }), totalDuration = report.TotalDuration.TotalMilliseconds }; await context.Response.WriteAsync(JsonSerializer.Serialize(result)); } }); app.Run();