using Autofac;
using Autofac.Extensions.DependencyInjection;
using ERP.Framework.Config;
using ERP.Framework.Constants;
using ERP.Framework.Extensions;
using ERP.Framework.Filter;
using ERP.Framework.Logger;
using ERP.Framework.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Serilog;
namespace ERP.Core
{
public static class Application
{
///
/// 初始化模块项目
///
///
///
///
public static WebApplicationBuilder InitApplication(this WebApplicationBuilder builder)
{
// 获取配置项
var redisConfig = builder.Configuration.GetSection(FrameworkConstant.REDIS).Get();
var logConfig = builder.Configuration.GetSection(FrameworkConstant.LOG_CONFIG).Get();
Log.Logger = LoggerBuilder.CreateLogger(logConfig);
// 处理Id生成配置
builder.Configuration.InitIdGenerater();
// DI
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer(builder =>
{
builder.InitAutofac();
});
// 注入HttpContext
builder.Services.AddHttpContextAccessor();
// 缓存注册
builder.Services.AddCache(redisConfig);
// EntityFrameworkCore
builder.Services.AddEntityFrameworkMySql();
// 跨域
builder.Services.AddCorsAccessor();
// Todo 任务队列
// Todo 任务调度
// Todo 添加MiniProfiler 性能分析
// Swagger
builder.Services.AddSwagger();
// 校验异常拦截
// 全局异常拦截
// Json序列化
builder.Services
.AddControllers(options =>
{
options.Filters.Add(new GlobalActionFilter());
options.Filters.Add(new GlobalExceptionFilter());
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
options.SerializerSettings.DateFormatString = DateTimeConstant.DATE_LONG;
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //忽略循环引用
//options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //动态对象属性名大写
//options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
//options.SerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // DateTimeOffset 异常
});
// 国际化处理
builder.Services.AddLocalization();
// Todo 事务总线 Redis消息队列 RabbitMQ 消息队列
//builder.Services.AddEventBus()
// 可添加 AddOauth2() 第三方授权或SSO
// AddElasticSerch() 配置ElasticSearc
// AddRateLimiting 限流
builder.Services.AddEndpointsApiExplorer();
// 权鉴中间件
builder.Services.AddScoped();
builder.Services.AddDbContext();
return builder;
}
public static void InitConfigure(this IApplicationBuilder app)
{
app.UseHttpsRedirection();
app.UseI18N();
app.UseAuthenticationMiddleware();
app.UseSwagger();
app.UseSwaggerUI();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}