xxyy
2025-03-10 85fd548c3948b4ded198f304204e9ce602761edc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using WIDESEA_Core.Helper;
using WIDESEA_Core.Extensions;
using WIDESEA_Core.Middlewares;
using System.Reflection;
using WIDESEA_Core.Filter;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System.Text;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using WIDESEA_Core;
using WIDESEA_Core.BaseServices;
using Autofac.Extensions.DependencyInjection;
using Autofac;
using WIDESEA_WMSServer.Filter;
using WIDESEA_Core.Authorization;
using WIDESEA_Core.Core;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;
using WIDESEA_StorageTaskServices;
using Autofac.Core;
using WIDESEA_Cache;
using SimpleRedis;
using WIDESEA_DTO.WMS;
using static NewLife.Remoting.ApiHttpClient;
using NewLife.Windows;
using WIDESEA_Core.Enums;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterModule(new AutofacModuleRegister());//´øÓнӿڲãµÄ·þÎñ×¢Èë
    builder.RegisterModule<AutofacPropertityModuleReg>();//
}).ConfigureAppConfiguration((hostingContext, config) =>
{
    hostingContext.Configuration.ConfigureApplication();
    config.Sources.Clear();
    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
}); ;
builder.ConfigureApplication();
 
// 2¡¢ÅäÖ÷þÎñ
builder.Services.AddSingleton(new AppSettings(builder.Configuration));//×¢²á
builder.Services.AddAllOptionRegister();//¶ÁÈ¡ÅäÖÃÎļþ
builder.Services.AddMemoryCacheSetup();//»º´æ
builder.Services.AddSqlsugarSetup();//SqlSugar Æô¶¯·þÎñ
builder.Services.AddInitializationHostServiceSetup();//Ó¦Óóõʼ»¯·þÎñ×¢Èë
builder.Services.AddDbSetup();//Db Æô¶¯·þÎñ
 
//todo ³õʼ»¯Ä£ÐÍÑéÖ¤ÅäÖÃ
//builder.Services.UseMethodsModelParameters().UseMethodsGeneralParameters();
//builder.Services.AddSingleton<IObjectModelValidator>(new NullObjectModelValidator());
 
builder.Services.AddAutoMapperSetup();
 
builder.Services.AddCorsSetup();
builder.Services.AddMiniProfilerSetup();
 
builder.Services.AddSwaggerSetup();
 
builder.Services.AddJobSetup();//ÈÎÎñµ÷¶È Æô¶¯·þÎñ
 
builder.Services.AddHttpContextSetup();
 
//todo
builder.Services.AddMvc(options =>
{
    options.Filters.Add(typeof(ApiAuthorizeFilter));
    //options.Filters.Add(typeof(ActionExecuteFilter));
    //  options.SuppressAsyncSuffixInActionNames = false;
});
 
builder.Services.AddAuthorizationSetup();
 
builder.Services.AddIpPolicyRateLimitSetup(builder.Configuration);//IPLimitÏÞÁ÷ Æô¶¯·þÎñ
 
builder.Services.AddScoped<UseServiceDIAttribute>();
 
//builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
 
builder.Services.AddHttpClient();
 
builder.Services.AddControllers(o =>
{
    o.Filters.Add(typeof(GlobalExceptionsFilter));//È«¾ÖÒì³£
    //todo
    //o.Conventions.Insert(0, new GlobalRoutePrefixFilter(new RouteAttribute(RoutePrefix.Name)));//·ÓÉ
})
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
    //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
    options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
    options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
 
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
 
builder.Services.AddSwaggerGen(c =>
{
    // ÆôÓÃXML×¢½â
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    if (File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath);
    }
});
 
builder.Services.AddHostedService<MyBackgroundService>();
 
//»º´æÉèÖÃÅäÖÃתʵÌå
builder.Services.AddConfigurableOptions<CacheSettingsOptions>();
//½ûÖ¹ÔÚÖ÷»úÆô¶¯Ê±Í¨¹ý App.GetOptions<TOptions> »ñȡѡÏÈçÐè»ñÈ¡ÅäÖÃÑ¡ÏîÀíӦͨ¹ý App.GetConfig<TOptions>("ÅäÖýڵã", true)¡£
var cacheSettings = AppSettings.Configuration.GetSection("CacheSettings").Get<CacheSettingsOptions>();
//Èç¹ûÓÐredisÁ¬½Ó×Ö·û´®
if (cacheSettings.UseRedis)
{
    var connectionString =
        $"server={cacheSettings.RedisSettings.Address};db={cacheSettings.RedisSettings.Db}";
    //×¢Èëredis
    builder.Services.AddSimpleRedis(connectionString);
    builder.Services.AddScoped<ISimpleCacheService, RedisCacheService>();
}
else
{
    builder.Services.AddScoped<ISimpleCacheService, MemoryCacheService>();
}
 
 
var app = builder.Build();
 
// ÑéÖ¤ Redis ·þÎñÊÇ·ñ³É¹¦×¢²á
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    var redisService = services.GetService<ISimpleCacheService>();
    if (redisService == null)
    {
        WIDESEA_Core.Helper.ConsoleHelper.WriteErrorLine("Redis ·þÎñδ³É¹¦×¢²á");
    }
    else
    {
        WIDESEA_Core.Helper.ConsoleHelper.WriteSuccessLine("Redis ·þÎñÒѳɹ¦×¢²á");
    }
}
 
// 3¡¢ÅäÖÃÖмä¼þ
app.UseMiniProfiler();//ÐÔÄÜ·ÖÎöÆ÷
app.ConfigureApplication();//ÅäÖÃÎļþ
app.UseApplicationSetup();//Æô¶¯ÅäÖÃ
app.UseSession();
//if (app.Environment.IsDevelopment())
//{
    //todo
    //app.UseSwaggerAuthorized();
    app.UseSwaggerMiddle(() => Assembly.GetExecutingAssembly().GetManifestResourceStream("WIDESEA_WMSServer.index.html"));
//}//ÅжÏÊÇ·ñÐèÒª´ò¿ªswagger
 
app.UseIpLimitMiddle();
app.UseApiLogMiddleware();
//todo
//app.UseRecordAccessLogsMiddle();
 
app.UseCors(AppSettings.app(new string[] { "Cors", "PolicyName" }));
 
//DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
//defaultFilesOptions.DefaultFileNames.Clear();
//defaultFilesOptions.DefaultFileNames.Add("index.html");
//app.UseDefaultFiles(defaultFilesOptions);
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseStatusCodePages();
 
app.UseRouting();
 
 
app.UseAuthentication();
app.UseAuthorization();
 
 
app.MapControllers();
 
//ͨ¹ý App.GetOptions<TOptions> »ñȡѡÏî
var cacheSettingsb = App.GetOptions<CacheSettingsOptions>();
//Èç¹ûÐèÒªÇå³ý»º´æ
if (cacheSettingsb.UseRedis && cacheSettingsb.RedisSettings.ClearRedis)
{
    var redis = app.Services.CreateScope().ServiceProvider.GetService<ISimpleCacheService>(); //»ñÈ¡redis·þÎñ
    // É¾³ýredisµÄkey
    redis.DelByPattern(CacheConst.Cache_Prefix);
 
    WIDESEA_Core.Helper.ConsoleHelper.WriteInfoLine("ÕýÔÚ»º´æ¿â´æÐÅÏ¢");
    var stockInfoList = await SqlSugarHelper.DbWMS.Queryable<DtStockInfo>()
        .Where(x => x.LocationInfo.LocationStatus == (int)LocationEnum.InStock).IncludesAllFirstLayer().ToListAsync();
    // »º´æ¿â´æÐÅÏ¢
    foreach (var item in stockInfoList)
    {
        item.StockInfoDetails = new List<DtStockInfoDetail>() { { item.StockInfoDetails[0] } };
        redis.HashAdd(CacheConst.Cache_DtStockInfo, item.PalletCode, item);
    }
    WIDESEA_Core.Helper.ConsoleHelper.WriteInfoLine("»º´æ¿â´æÐÅÏ¢Íê³É");
}
 
app.Run();