BusinessHostModule.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using Business.Core.Attributes;
  2. using Business.Core.Utilities;
  3. using Business.Domain;
  4. using Business.EntityFrameworkCore;
  5. using Business.MultiTenancy;
  6. using Bussiness.MongoDB;
  7. using GZY.Quartz.MUI.Extensions;
  8. using Microsoft.AspNetCore.Authentication.JwtBearer;
  9. using Microsoft.AspNetCore.Builder;
  10. using Microsoft.AspNetCore.Cors;
  11. using Microsoft.AspNetCore.DataProtection;
  12. using Microsoft.AspNetCore.Hosting;
  13. using Microsoft.EntityFrameworkCore;
  14. using Microsoft.Extensions.Configuration;
  15. using Microsoft.Extensions.DependencyInjection;
  16. using Microsoft.Extensions.Hosting;
  17. using Microsoft.OpenApi.Models;
  18. using MongoDB.Driver;
  19. using NLog;
  20. using Quartz;
  21. using StackExchange.Redis;
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Data;
  25. using System.IO;
  26. using System.Linq;
  27. using Volo.Abp;
  28. using Volo.Abp.AspNetCore.ExceptionHandling;
  29. using Volo.Abp.AspNetCore.MultiTenancy;
  30. using Volo.Abp.AspNetCore.Mvc;
  31. using Volo.Abp.AspNetCore.Serilog;
  32. using Volo.Abp.Autofac;
  33. using Volo.Abp.Caching;
  34. using Volo.Abp.EntityFrameworkCore.MySQL;
  35. using Volo.Abp.Localization;
  36. using Volo.Abp.Modularity;
  37. using Volo.Abp.MultiTenancy;
  38. using Volo.Abp.VirtualFileSystem;
  39. namespace Business
  40. {
  41. [DependsOn(
  42. typeof(AbpAutofacModule),
  43. typeof(AbpEntityFrameworkCoreMySQLModule),
  44. typeof(BusinessHttpApiModule),
  45. typeof(BusinessApplicationModule),
  46. typeof(BusinessEntityFrameworkCoreModule),
  47. typeof(BussinessMongoDbModule),
  48. typeof(AbpAspNetCoreMultiTenancyModule),
  49. typeof(AbpAspNetCoreSerilogModule)
  50. )]
  51. public class BusinessHostModule : AbpModule
  52. {
  53. private const string DefaultCorsPolicyName = "Default";
  54. public override void ConfigureServices(ServiceConfigurationContext context)
  55. {
  56. var configuration = context.Services.GetConfiguration();
  57. var hostingEnvironment = context.Services.GetHostingEnvironment();
  58. //ConfigureConventionalControllers();
  59. ConfigureMultiTenancy();
  60. ConfigureAuthentication(context, configuration);
  61. ConfigureLocalization();
  62. ConfigureCache(configuration);
  63. ConfigureVirtualFileSystem(context, hostingEnvironment);
  64. //ConfigureRedis(context, configuration, hostingEnvironment);
  65. ConfigureCors(context, configuration);
  66. ConfigureSwaggerServices(context, configuration);
  67. ConfigureQuartz(context, configuration);
  68. ConfigureMongoDB(configuration);
  69. if (hostingEnvironment.IsDevelopment())
  70. {
  71. Configure<AbpExceptionHandlingOptions>(options =>
  72. {
  73. options.SendExceptionsDetailsToClients = true;
  74. });
  75. }
  76. }
  77. private void ConfigureConventionalControllers()
  78. {
  79. Configure<AbpAspNetCoreMvcOptions>(options =>
  80. {
  81. options.ConventionalControllers.Create(typeof(BusinessApplicationModule).Assembly);
  82. });
  83. }
  84. private void ConfigureMultiTenancy()
  85. {
  86. Configure<AbpMultiTenancyOptions>(options =>
  87. {
  88. options.IsEnabled = true;
  89. });
  90. }
  91. private void ConfigureQuartz(ServiceConfigurationContext context, IConfiguration configuration)
  92. {
  93. //程序启动执行一次日志分表检查,可以自己初始化避免需要部署脚本
  94. LogManager.Configuration.Install(new NLog.Config.InstallationContext());//每天0点执行一次
  95. context.Services.AddQuartz(q =>
  96. {
  97. //q.UseMicrosoftDependencyInjectionScopedJobFactory();
  98. //// Just use the name of your job that you created in the Jobs folder.
  99. //var jobKey = new JobKey("SyncDataJob");
  100. //q.AddJob<SyncMySQLDataJob>(opts => opts.WithIdentity(jobKey));
  101. //q.AddTrigger(opts => opts
  102. // .ForJob(jobKey)
  103. // .WithIdentity("SyncDataJob-trigger")
  104. // .WithCronSchedule("0 38 10 * * ?")
  105. // .WithDescription("定时同步MySQL基础数据到MongoDB"));
  106. //var NLogJobKey = new JobKey("NLogJob");
  107. //q.AddJob<NLogJob>(opts => opts.WithIdentity(NLogJobKey));
  108. //q.AddTrigger(opts => opts
  109. // .ForJob(NLogJobKey)
  110. // .WithIdentity("NLogJob-trigger")
  111. // .WithCronSchedule("0 01 01 * * ?")
  112. // .WithDescription("定时创建NLog日志按月分表"));
  113. //var WMSJobKey = new JobKey("WMSJob");
  114. //q.AddJob<WMSJob>(opts => opts.WithIdentity(WMSJobKey));
  115. //q.AddTrigger(opts => opts
  116. // .ForJob(WMSJobKey)
  117. // .WithIdentity("WMSJob-trigger")
  118. // .WithCronSchedule("0 32 15 * * ?")
  119. // .WithDescription("定时同步WMS物料订单等基础数据到MySQL"));
  120. //var ProductionScheduleJobKey = new JobKey("ProductionScheduleJob");
  121. //q.AddJob<ProductionScheduleJob>(opts => opts.WithIdentity(ProductionScheduleJobKey));
  122. //q.AddTrigger(opts => opts
  123. // .ForJob(ProductionScheduleJobKey)
  124. // .WithIdentity("ProductionScheduleJob-trigger")
  125. // .WithCronSchedule("0 01 01 * * ?")
  126. // .WithDescription("定时排产任务"));
  127. });
  128. context.Services.AddQuartzServer(options =>
  129. {
  130. // when shutting down we want jobs to complete gracefully
  131. options.WaitForJobsToComplete = true;
  132. });
  133. context.Services.AddQuartzUI();
  134. context.Services.AddQuartzClassJobs(); //添加本地调度任务访问
  135. context.Services.AddQuartzHostedService(options =>
  136. {
  137. // when shutting down we want jobs to complete gracefully
  138. options.WaitForJobsToComplete = true;
  139. });
  140. }
  141. /// <summary>
  142. /// MongoDB依赖注入
  143. /// </summary>
  144. /// <param name="context"></param>
  145. /// <param name="configuration"></param>
  146. private void ConfigureMongoDB(IConfiguration configuration)
  147. {
  148. //[Index(nameof(bom_number), nameof(item_number), nameof(version), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  149. var indexModel_mo_ic_bom = new CreateIndexModel<mo_ic_bom>(
  150. Builders<mo_ic_bom>.IndexKeys.
  151. Ascending(_ => _.bom_number).
  152. Ascending(_ => _.item_number).
  153. Ascending(_ => _.version).
  154. Ascending(_ => _.tenant_id).
  155. Ascending(_ => _.factory_id)
  156. , new CreateIndexOptions
  157. {
  158. Name = "bom_number_1_item_number_1_version_1_tenant_id_1_factory_id_1",
  159. Sparse = true,
  160. Background = true,
  161. Unique = true, //唯一值索引
  162. });
  163. //mongoCollection_mo_ic_bom.Indexes.CreateOne(indexModel_mo_ic_bom);
  164. MongoHelper<mo_ic_bom>.CreatIndexAsync(indexModel_mo_ic_bom);
  165. //[Index(nameof(bom_number), nameof(item_number), nameof(version), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  166. var indexModel_mo_ic_bom_child = new CreateIndexModel<mo_ic_bom_child>(
  167. Builders<mo_ic_bom_child>.IndexKeys.
  168. Ascending(_ => _.bom_number).
  169. Ascending(_ => _.item_number).
  170. Ascending(_ => _.version).
  171. Ascending(_ => _.tenant_id).
  172. Ascending(_ => _.factory_id)
  173. , new CreateIndexOptions
  174. {
  175. Name = "bom_number_1_item_number_1_version_1_tenant_id_1_factory_id_1",
  176. Sparse = true,
  177. Background = true,
  178. Unique = true, //唯一值索引
  179. });
  180. //mongoCollection_mo_ic_bom_child.Indexes.CreateOne(indexModel_mo_ic_bom_child);
  181. MongoHelper<mo_ic_bom_child>.CreatIndexAsync(indexModel_mo_ic_bom_child);
  182. //[Index(nameof(number), nameof(fversion), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  183. var indexModel_mo_ic_item = new CreateIndexModel<mo_ic_item>(
  184. Builders<mo_ic_item>.IndexKeys.
  185. Ascending(_ => _.number).
  186. Ascending(_ => _.fversion).
  187. Ascending(_ => _.tenant_id).
  188. Ascending(_ => _.factory_id)
  189. , new CreateIndexOptions
  190. {
  191. Name = "number_1_fversion_1_tenant_id_1_factory_id_1",
  192. Sparse = true,
  193. Background = true,
  194. Unique = true, //唯一值索引
  195. });
  196. //mongoCollection_mo_ic_item.Indexes.CreateOne(indexModel_mo_ic_item);
  197. MongoHelper<mo_ic_item>.CreatIndexAsync(indexModel_mo_ic_item);
  198. //[Index(nameof(icitem_number), nameof(fversion), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  199. var indexModel_mo_ic_item_stock = new CreateIndexModel<mo_ic_item_stock>(
  200. Builders<mo_ic_item_stock>.IndexKeys.
  201. Ascending(_ => _.icitem_number).
  202. Ascending(_ => _.fversion).
  203. Ascending(_ => _.tenant_id).
  204. Ascending(_ => _.factory_id).
  205. Ascending(_ => _.bang_id)
  206. , new CreateIndexOptions
  207. {
  208. Name = "icitem_number_1_fversion_1_tenant_id_1_factory_id_1",
  209. Sparse = true,
  210. Background = true,
  211. Unique = true, //唯一值索引
  212. });
  213. //mongoCollection_mo_ic_item_stock.Indexes.CreateOne(indexModel_mo_ic_item_stock);
  214. MongoHelper<mo_ic_item_stock>.CreatIndexAsync(indexModel_mo_ic_item_stock);
  215. //[Index(nameof(po_billno), nameof(polist_row), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  216. var indexModel_mo_srm_po_list = new CreateIndexModel<mo_srm_po_list>(
  217. Builders<mo_srm_po_list>.IndexKeys.
  218. Ascending(_ => _.po_billno).
  219. Ascending(_ => _.polist_row).
  220. Ascending(_ => _.tenant_id).
  221. Ascending(_ => _.factory_id).
  222. Ascending(_ => _.bang_id)
  223. , new CreateIndexOptions
  224. {
  225. Name = "po_billno_1_polist_row_1_tenant_id_1_factory_id_1",
  226. Sparse = true,
  227. Background = true,
  228. Unique = true, //唯一值索引
  229. });
  230. //mongoCollection_mo_srm_po_list.Indexes.CreateOne(indexModel_mo_srm_po_list);
  231. MongoHelper<mo_srm_po_list>.CreatIndexAsync(indexModel_mo_srm_po_list);
  232. //[Index(nameof(po_billno), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  233. CreateIndexModel<mo_srm_po_main> indexModel_mo_srm_po_main = new CreateIndexModel<mo_srm_po_main>(
  234. Builders<mo_srm_po_main>.IndexKeys.
  235. Ascending(_ => _.po_billno).
  236. Ascending(_ => _.tenant_id).
  237. Ascending(_ => _.factory_id).
  238. Ascending(_ => _.bang_id)
  239. , new CreateIndexOptions
  240. {
  241. Name = "po_billno_1_tenant_id_1_factory_id_1",
  242. Sparse = true,
  243. Background = true,
  244. Unique = true, //唯一值索引
  245. });
  246. //mongoCollection_mo_srm_po_main.Indexes.CreateOne(indexModel_mo_srm_po_main);
  247. MongoHelper<mo_srm_po_main>.CreatIndexAsync(indexModel_mo_srm_po_main);
  248. //[Index(nameof(pr_billno), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  249. CreateIndexModel<mo_srm_pr_main> indexModel_mo_srm_pr_main = new CreateIndexModel<mo_srm_pr_main>(
  250. Builders<mo_srm_pr_main>.IndexKeys.
  251. Ascending(_ => _.pr_billno).
  252. Ascending(_ => _.tenant_id).
  253. Ascending(_ => _.factory_id).
  254. Ascending(_ => _.bang_id)
  255. , new CreateIndexOptions
  256. {
  257. Name = "pr_billno_1_tenant_id_1_factory_id_1",
  258. Sparse = true,
  259. Background = true,
  260. Unique = true, //唯一值索引
  261. });
  262. //mongoCollection_mo_srm_pr_main.Indexes.CreateOne(indexModel_mo_srm_pr_main);
  263. MongoHelper<mo_srm_pr_main>.CreatIndexAsync(indexModel_mo_srm_pr_main);
  264. //[Index(nameof(number), nameof(supplier_number), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  265. CreateIndexModel<mo_srm_purchase> indexModel_mo_srm_purchase = new CreateIndexModel<mo_srm_purchase>(
  266. Builders<mo_srm_purchase>.IndexKeys.
  267. Ascending(_ => _.number).
  268. Ascending(_ => _.supplier_number).
  269. Ascending(_ => _.tenant_id).
  270. Ascending(_ => _.factory_id).
  271. Ascending(_ => _.bang_id)
  272. , new CreateIndexOptions
  273. {
  274. Name = "number_1_supplier_number_1_tenant_id_1_factory_id_1",
  275. Sparse = true,
  276. Background = true,
  277. Unique = true, //唯一值索引
  278. });
  279. //mongoCollection_mo_srm_purchase.Indexes.CreateOne(indexModel_mo_srm_purchase);
  280. MongoHelper<mo_srm_purchase>.CreatIndexAsync(indexModel_mo_srm_purchase);
  281. //[Index(nameof(supplier_no), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  282. CreateIndexModel<mo_srm_supplier> indexModel_mo_srm_supplier = new CreateIndexModel<mo_srm_supplier>(
  283. Builders<mo_srm_supplier>.IndexKeys.
  284. Ascending(_ => _.supplier_no).
  285. Ascending(_ => _.tenant_id).
  286. Ascending(_ => _.factory_id)
  287. , new CreateIndexOptions
  288. {
  289. Name = "supplier_no_1_tenant_id_1_factory_id_1",
  290. Sparse = true,
  291. Background = true,
  292. Unique = true, //唯一值索引
  293. });
  294. //mongoCollection_mo_srm_supplier.Indexes.CreateOne(indexModel_mo_srm_supplier);
  295. MongoHelper<mo_srm_supplier>.CreatIndexAsync(indexModel_mo_srm_supplier);
  296. }
  297. private void ConfigureCache(IConfiguration configuration)
  298. {
  299. Configure<AbpDistributedCacheOptions>(options =>
  300. {
  301. options.KeyPrefix = "dopbiz:";
  302. });
  303. }
  304. private void ConfigureVirtualFileSystem(ServiceConfigurationContext context, IWebHostEnvironment webHostEnvironment)
  305. {
  306. //var hostingEnvironment = context.Services.GetHostingEnvironment();
  307. if (webHostEnvironment.IsDevelopment())
  308. {
  309. Configure<AbpVirtualFileSystemOptions>(options =>
  310. {
  311. options.FileSets.ReplaceEmbeddedByPhysical<BusinessDomainModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Domain"));
  312. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationContractsModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application.Contracts"));
  313. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application"));
  314. });
  315. }
  316. }
  317. private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
  318. {
  319. context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  320. .AddJwtBearer(options =>
  321. {
  322. options.Authority = configuration["AuthServer:Authority"];
  323. options.RequireHttpsMetadata = false;
  324. options.Audience = "BusinessService";
  325. });
  326. }
  327. private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
  328. {
  329. if (configuration["UseSwagger"] == "true")
  330. {
  331. context.Services.AddSwaggerGen(options =>
  332. {
  333. options.SwaggerDoc("v1", new OpenApiInfo { Title = "Business Service API", Version = "v1" });
  334. options.DocInclusionPredicate((docName, description) => true);
  335. options.CustomSchemaIds(type => type.FullName);
  336. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  337. {
  338. Description = "请输入JWT令牌,例如:Bearer 12345abcdef",
  339. Name = "Authorization",
  340. In = ParameterLocation.Header,
  341. Type = SecuritySchemeType.ApiKey,
  342. Scheme = "Bearer"
  343. });
  344. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  345. {
  346. {
  347. new OpenApiSecurityScheme
  348. {
  349. Reference = new OpenApiReference
  350. {
  351. Type = ReferenceType.SecurityScheme,
  352. Id = "Bearer"
  353. },
  354. Scheme = "oauth2",
  355. Name = "Bearer",
  356. In = ParameterLocation.Header,
  357. },
  358. new List<string>()
  359. }
  360. });
  361. });
  362. }
  363. }
  364. private void ConfigureLocalization()
  365. {
  366. Configure<AbpLocalizationOptions>(options =>
  367. {
  368. options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
  369. options.Languages.Add(new LanguageInfo("en", "en", "English"));
  370. options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
  371. options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
  372. options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
  373. options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
  374. });
  375. }
  376. private void ConfigureRedis(
  377. ServiceConfigurationContext context,
  378. IConfiguration configuration,
  379. IWebHostEnvironment hostingEnvironment)
  380. {
  381. context.Services.AddStackExchangeRedisCache(options =>
  382. {
  383. options.Configuration = configuration["Redis:Configuration"];
  384. });
  385. if (!hostingEnvironment.IsDevelopment())
  386. {
  387. var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
  388. context.Services
  389. .AddDataProtection()
  390. .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
  391. }
  392. }
  393. private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
  394. {
  395. context.Services.AddCors(options =>
  396. {
  397. options.AddPolicy(DefaultCorsPolicyName, builder =>
  398. {
  399. builder
  400. .WithOrigins(
  401. configuration["App:CorsOrigins"]
  402. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  403. .Select(o => o.RemovePostFix("/"))
  404. .ToArray()
  405. )
  406. .WithAbpExposedHeaders()
  407. .SetIsOriginAllowedToAllowWildcardSubdomains()
  408. .AllowAnyHeader()
  409. .AllowAnyMethod()
  410. .AllowCredentials();
  411. });
  412. });
  413. }
  414. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  415. {
  416. var app = context.GetApplicationBuilder();
  417. var configuration = context.GetConfiguration();
  418. app.UseCorrelationId();
  419. app.UseStaticFiles();
  420. app.UseRouting();
  421. app.UseCors(DefaultCorsPolicyName);
  422. app.UseAuthentication();
  423. app.UseAbpClaimsMap();
  424. if (MultiTenancyConsts.IsEnabled)
  425. {
  426. app.UseMultiTenancy();
  427. }
  428. app.UseAbpRequestLocalization();
  429. if (configuration["UseSwagger"] == "true")
  430. {
  431. app.UseSwagger();
  432. app.UseSwaggerUI(options =>
  433. {
  434. options.SwaggerEndpoint("/swagger/v1/swagger.json", "Business Service API");
  435. });
  436. }
  437. app.UseAuditing();
  438. app.UseAbpSerilogEnrichers();
  439. app.UseUnitOfWork();
  440. app.UseConfiguredEndpoints();
  441. app.UseQuartz();
  442. //AsyncHelper.RunSync(async () =>
  443. //{
  444. // using (var scope = context.ServiceProvider.CreateScope())
  445. // {
  446. // await scope.ServiceProvider
  447. // .GetRequiredService<IDataSeeder>()
  448. // .SeedAsync();
  449. // }
  450. //});
  451. }
  452. }
  453. }