You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

252 lines
6.9 KiB

using System.Globalization;
using System.Text;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Entity.Dto.Resp;
using HybirdFrameworkCore.Auth;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.AutoTask;
using HybirdFrameworkCore.Configuration;
using HybirdFrameworkCore.Entity;
using HybirdFrameworkCore.Job;
using HybirdFrameworkCore.Redis;
using log4net;
using log4net.Util;
using Mapster;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Localization;
using Microsoft.IdentityModel.Tokens;
using Service.Charger.Client;
using Service.Execute;
using Service.Fire.Client;
using Service.Led;
using Service.Padar.Client;
using Service.PlcAfrica.Client;
using Service.RealTime;
using Service.Sound.SoundClient;
using Service.Ups;
using Service.UpsAfrica.Client;
using SqlSugar;
using SqlSugar.IOC;
using AppInfo = HybirdFrameworkCore.Autofac.AppInfo;
var builder = WebApplication.CreateBuilder(args);
var log = LogManager.GetLogger(typeof(Program));
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(cb =>
{
cb.Register(c =>
{
var db = new SqlSugarScope(new ConnectionConfig
{
ConfigId = AppSettingsConstVars.ConfigId,
ConnectionString = AppSettingsConstVars.DbSqlConnection, // 设置数据库连接字符串
DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识,请设置为 InitKeyType.Attr
}, c =>
{
c.Aop.OnLogExecuting = (sql, pars) =>
{
string nativeSql = UtilMethods.GetNativeSql(sql, pars);
log.Info(nativeSql);
};
});
return db;
}).As<ISqlSugarClient>().SingleInstance();
cb.RegisterModule(new AutofacModuleRegister());
});
// 注册自定义映射
var mapper = new SysMenuMapper();
mapper.Register(TypeAdapterConfig.GlobalSettings);
//在 Autofac 容器中注册IHttpContextAccessor 服务
builder.Services.AddHttpContextAccessor();
//跨域
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy
(builde =>
{
builde
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}
);
});
//redis
var redisConnectionString = AppSettingsHelper.GetContent("Redis", "Connection");
var instanceName = AppSettingsHelper.GetContent("Redis", "InstanceName"); //默认数据库
var defaultDb = int.Parse(AppSettingsHelper.GetContent("Redis", "DefaultDB") ?? "0");
if (redisConnectionString != null && instanceName != null)
builder.Services.AddSingleton(new RedisHelper(redisConnectionString, instanceName, defaultDb));
builder.Services.AddControllers().AddJsonOptions(configure =>
{
configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
// configure.JsonSerializerOptions.Converters.Add(new LongJsonConverter());
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddSwaggerGen(c =>
{
var basePath = Path.GetDirectoryName(AppContext.BaseDirectory);
//c.IncludeXmlComments(Path.Combine(basePath, Assembly.GetExecutingAssembly().GetName().Name+".xml"), true);
c.IncludeXmlComments(Path.Combine(basePath, "WebStarter.xml"), true);
c.IncludeXmlComments(Path.Combine(basePath, "Entity.xml"), true);
c.IncludeXmlComments(Path.Combine(basePath, "HybirdFrameworkCore.xml"), true);
});
bool.TryParse(AppSettingsHelper.GetContent("SignalR", "enable"), out var signalrEnabled);
if (signalrEnabled)
{
builder.Services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
options.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
// 添加jwt验证
var securityKey = AppSettingsHelper.GetContent("TokenOptions", "SecurityKey");
var audience = AppSettingsHelper.GetContent("TokenOptions", "Audience");
var issuer = AppSettingsHelper.GetContent("TokenOptions", "Issuer");
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => //配置鉴权逻辑
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = issuer,
ValidAudience = audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)),
ValidateLifetime = false
};
});
// 添加国际化支持
builder.Services.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();
app.UseStaticFiles();
app.UseAuthorization();
app.UseCors();
app.MapControllers();
if (signalrEnabled)
{
app.MapHub<MyHub>("/realtime");
}
var list = AppSettingsHelper.GetContent("Kestrel", "Endpoints", "http", "Url");
foreach (var s in list.Split(";"))
{
log.Info($"use url={s}");
app.Urls.Add(s);
}
AppInfo.Container = app.Services.GetAutofacRoot();
////云平台
//if (AppSettingsHelper.GetBool("cloud", "enable"))
//{
// CloudClientMgr.Init();
//}
////PLC
if (AppSettingsHelper.GetBool("plc", "enable"))
{
//ClientMgr.InitClient();
}
FireMgr.UpsInit();
//雷达
if (AppSettingsHelper.GetBool("padar", "enable"))
{
PadarMgr.InitClient();
}
if (AppSettingsHelper.GetBool("led", "enable"))
{
LedClient.Init(AppSettingsHelper.GetContent("led", "ip"), Convert.ToInt32(AppSettingsHelper.GetContent("led", "port")));
}
////启动换电流程
if (AppSettingsHelper.GetBool("swap", "enable"))
{
StationSoftMgr.SwappingStateMachineStart();
}
PadarMgr.InitClient();
////现场调试plc连接
AppInfo.Container = app.Services.GetAutofacRoot();
//ClientMgr.InitClient();
//ups
if (AppSettingsHelper.GetBool("ups", "enable"))
{
UpsMgr.UpsInit();
}
//ups
if (AppSettingsHelper.GetBool("upsAfrica", "enable"))
{
UpsAfricaMgr.UpsInit();
}
PlcAfricaMgr.PlcInit();
//new SoundClient().SoundConn();
//TaskInit.Init();
//PadarMgr.InitClient();
TaskInit.Init();
//QuartzSchedulerFactory.Init();
//app.Lifetime.ApplicationStopping.Register(QuartzSchedulerFactory.Shutdown);
// 配置多语言支持
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("id"),
new CultureInfo("zh")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("zh"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
});
//var dateTime = SysInfo.Now;
app.Run();