BusinessHostModule.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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(_ => _.company_id).
  156. Ascending(_ => _.factory_id)
  157. , new CreateIndexOptions
  158. {
  159. Name = "bom_number_1_item_number_1_version_1_tenant_id_1_factory_id_1",
  160. Sparse = true,
  161. Background = true,
  162. Unique = true, //唯一值索引
  163. });
  164. //mongoCollection_mo_ic_bom.Indexes.CreateOne(indexModel_mo_ic_bom);
  165. MongoHelper<mo_ic_bom>.CreatIndexAsync(indexModel_mo_ic_bom);
  166. //[Index(nameof(bom_number), nameof(item_number), nameof(version), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  167. var indexModel_mo_ic_bom_child = new CreateIndexModel<mo_ic_bom_child>(
  168. Builders<mo_ic_bom_child>.IndexKeys.
  169. Ascending(_ => _.bom_number).
  170. Ascending(_ => _.item_number).
  171. Ascending(_ => _.version).
  172. Ascending(_ => _.tenant_id).
  173. Ascending(_ => _.company_id).
  174. Ascending(_ => _.factory_id)
  175. , new CreateIndexOptions
  176. {
  177. Name = "bom_number_1_item_number_1_version_1_tenant_id_1_factory_id_1",
  178. Sparse = true,
  179. Background = true,
  180. Unique = true, //唯一值索引
  181. });
  182. //mongoCollection_mo_ic_bom_child.Indexes.CreateOne(indexModel_mo_ic_bom_child);
  183. MongoHelper<mo_ic_bom_child>.CreatIndexAsync(indexModel_mo_ic_bom_child);
  184. //[Index(nameof(number), nameof(fversion), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  185. var indexModel_mo_ic_item = new CreateIndexModel<mo_ic_item>(
  186. Builders<mo_ic_item>.IndexKeys.
  187. Ascending(_ => _.number).
  188. Ascending(_ => _.fversion).
  189. Ascending(_ => _.tenant_id).
  190. Ascending(_ => _.company_id).
  191. Ascending(_ => _.factory_id)
  192. , new CreateIndexOptions
  193. {
  194. Name = "number_1_fversion_1_tenant_id_1_factory_id_1",
  195. Sparse = true,
  196. Background = true,
  197. Unique = true, //唯一值索引
  198. });
  199. //mongoCollection_mo_ic_item.Indexes.CreateOne(indexModel_mo_ic_item);
  200. MongoHelper<mo_ic_item>.CreatIndexAsync(indexModel_mo_ic_item);
  201. //[Index(nameof(icitem_number), nameof(fversion), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  202. var indexModel_mo_ic_item_stock = new CreateIndexModel<mo_ic_item_stock>(
  203. Builders<mo_ic_item_stock>.IndexKeys.
  204. Ascending(_ => _.icitem_number).
  205. Ascending(_ => _.fversion).
  206. Ascending(_ => _.tenant_id).
  207. Ascending(_ => _.company_id).
  208. Ascending(_ => _.factory_id).
  209. Ascending(_ => _.bang_id)
  210. , new CreateIndexOptions
  211. {
  212. Name = "icitem_number_1_fversion_1_tenant_id_1_factory_id_1",
  213. Sparse = true,
  214. Background = true,
  215. Unique = true, //唯一值索引
  216. });
  217. //mongoCollection_mo_ic_item_stock.Indexes.CreateOne(indexModel_mo_ic_item_stock);
  218. MongoHelper<mo_ic_item_stock>.CreatIndexAsync(indexModel_mo_ic_item_stock);
  219. //[Index(nameof(po_billno), nameof(polist_row), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  220. /*var indexModel_mo_srm_po_list = new CreateIndexModel<mo_srm_po_list>(
  221. Builders<mo_srm_po_list>.IndexKeys.
  222. Ascending(_ => _.po_billno).
  223. Ascending(_ => _.polist_row).
  224. Ascending(_ => _.tenant_id).
  225. Ascending(_ => _.company_id).
  226. Ascending(_ => _.factory_id).
  227. Ascending(_ => _.bang_id)
  228. , new CreateIndexOptions
  229. {
  230. Name = "po_billno_1_polist_row_1_tenant_id_1_factory_id_1",
  231. Sparse = true,
  232. Background = true,
  233. Unique = true, //唯一值索引
  234. });
  235. //mongoCollection_mo_srm_po_list.Indexes.CreateOne(indexModel_mo_srm_po_list);
  236. MongoHelper<mo_srm_po_list>.CreatIndexAsync(indexModel_mo_srm_po_list);*/
  237. //[Index(nameof(po_billno), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  238. CreateIndexModel<mo_srm_po_main> indexModel_mo_srm_po_main = new CreateIndexModel<mo_srm_po_main>(
  239. Builders<mo_srm_po_main>.IndexKeys.
  240. Ascending(_ => _.po_billno).
  241. Ascending(_ => _.tenant_id).
  242. Ascending(_ => _.company_id).
  243. Ascending(_ => _.factory_id).
  244. Ascending(_ => _.bang_id)
  245. , new CreateIndexOptions
  246. {
  247. Name = "po_billno_1_tenant_id_1_factory_id_1",
  248. Sparse = true,
  249. Background = true,
  250. Unique = true, //唯一值索引
  251. });
  252. //mongoCollection_mo_srm_po_main.Indexes.CreateOne(indexModel_mo_srm_po_main);
  253. MongoHelper<mo_srm_po_main>.CreatIndexAsync(indexModel_mo_srm_po_main);
  254. /*//[Index(nameof(pr_billno), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  255. CreateIndexModel<mo_srm_pr_main> indexModel_mo_srm_pr_main = new CreateIndexModel<mo_srm_pr_main>(
  256. Builders<mo_srm_pr_main>.IndexKeys.
  257. Ascending(_ => _.pr_billno).
  258. Ascending(_ => _.tenant_id).
  259. Ascending(_ => _.company_id).
  260. Ascending(_ => _.factory_id).
  261. Ascending(_ => _.bang_id)
  262. , new CreateIndexOptions
  263. {
  264. Name = "pr_billno_1_tenant_id_1_factory_id_1",
  265. Sparse = true,
  266. Background = true,
  267. Unique = true, //唯一值索引
  268. });
  269. //mongoCollection_mo_srm_pr_main.Indexes.CreateOne(indexModel_mo_srm_pr_main);
  270. MongoHelper<mo_srm_pr_main>.CreatIndexAsync(indexModel_mo_srm_pr_main);*/
  271. //[Index(nameof(number), nameof(supplier_number), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  272. CreateIndexModel<mo_srm_purchase> indexModel_mo_srm_purchase = new CreateIndexModel<mo_srm_purchase>(
  273. Builders<mo_srm_purchase>.IndexKeys.
  274. Ascending(_ => _.number).
  275. Ascending(_ => _.supplier_number).
  276. Ascending(_ => _.tenant_id).
  277. Ascending(_ => _.company_id).
  278. Ascending(_ => _.factory_id).
  279. Ascending(_ => _.bang_id)
  280. , new CreateIndexOptions
  281. {
  282. Name = "number_1_supplier_number_1_tenant_id_1_factory_id_1",
  283. Sparse = true,
  284. Background = true,
  285. Unique = true, //唯一值索引
  286. });
  287. //mongoCollection_mo_srm_purchase.Indexes.CreateOne(indexModel_mo_srm_purchase);
  288. MongoHelper<mo_srm_purchase>.CreatIndexAsync(indexModel_mo_srm_purchase);
  289. //[Index(nameof(supplier_no), nameof(tenant_id), nameof(factory_id), IsUnique = true)]
  290. CreateIndexModel<mo_srm_supplier> indexModel_mo_srm_supplier = new CreateIndexModel<mo_srm_supplier>(
  291. Builders<mo_srm_supplier>.IndexKeys.
  292. Ascending(_ => _.supplier_no).
  293. Ascending(_ => _.tenant_id).
  294. Ascending(_ => _.company_id).
  295. Ascending(_ => _.factory_id)
  296. , new CreateIndexOptions
  297. {
  298. Name = "supplier_no_1_tenant_id_1_factory_id_1",
  299. Sparse = true,
  300. Background = true,
  301. Unique = true, //唯一值索引
  302. });
  303. //mongoCollection_mo_srm_supplier.Indexes.CreateOne(indexModel_mo_srm_supplier);
  304. MongoHelper<mo_srm_supplier>.CreatIndexAsync(indexModel_mo_srm_supplier);
  305. }
  306. private void ConfigureCache(IConfiguration configuration)
  307. {
  308. Configure<AbpDistributedCacheOptions>(options =>
  309. {
  310. options.KeyPrefix = "dopbiz:";
  311. });
  312. }
  313. private void ConfigureVirtualFileSystem(ServiceConfigurationContext context, IWebHostEnvironment webHostEnvironment)
  314. {
  315. //var hostingEnvironment = context.Services.GetHostingEnvironment();
  316. if (webHostEnvironment.IsDevelopment())
  317. {
  318. Configure<AbpVirtualFileSystemOptions>(options =>
  319. {
  320. options.FileSets.ReplaceEmbeddedByPhysical<BusinessDomainModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Domain"));
  321. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationContractsModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application.Contracts"));
  322. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application"));
  323. });
  324. }
  325. }
  326. private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
  327. {
  328. context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  329. .AddJwtBearer(options =>
  330. {
  331. options.Authority = configuration["AuthServer:Authority"];
  332. options.RequireHttpsMetadata = false;
  333. options.Audience = "BusinessService";
  334. });
  335. }
  336. private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
  337. {
  338. if (configuration["UseSwagger"] == "true")
  339. {
  340. context.Services.AddSwaggerGen(options =>
  341. {
  342. options.SwaggerDoc("v1", new OpenApiInfo { Title = "Business Service API", Version = "v1" });
  343. options.DocInclusionPredicate((docName, description) => true);
  344. options.CustomSchemaIds(type => type.FullName);
  345. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  346. {
  347. Description = "请输入JWT令牌,例如:Bearer 12345abcdef",
  348. Name = "Authorization",
  349. In = ParameterLocation.Header,
  350. Type = SecuritySchemeType.ApiKey,
  351. Scheme = "Bearer"
  352. });
  353. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  354. {
  355. {
  356. new OpenApiSecurityScheme
  357. {
  358. Reference = new OpenApiReference
  359. {
  360. Type = ReferenceType.SecurityScheme,
  361. Id = "Bearer"
  362. },
  363. Scheme = "oauth2",
  364. Name = "Bearer",
  365. In = ParameterLocation.Header,
  366. },
  367. new List<string>()
  368. }
  369. });
  370. });
  371. }
  372. }
  373. private void ConfigureLocalization()
  374. {
  375. Configure<AbpLocalizationOptions>(options =>
  376. {
  377. options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
  378. options.Languages.Add(new LanguageInfo("en", "en", "English"));
  379. options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
  380. options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
  381. options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
  382. options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
  383. });
  384. }
  385. private void ConfigureRedis(
  386. ServiceConfigurationContext context,
  387. IConfiguration configuration,
  388. IWebHostEnvironment hostingEnvironment)
  389. {
  390. context.Services.AddStackExchangeRedisCache(options =>
  391. {
  392. options.Configuration = configuration["Redis:Configuration"];
  393. });
  394. if (!hostingEnvironment.IsDevelopment())
  395. {
  396. var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
  397. context.Services
  398. .AddDataProtection()
  399. .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
  400. }
  401. }
  402. private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
  403. {
  404. context.Services.AddCors(options =>
  405. {
  406. options.AddPolicy(DefaultCorsPolicyName, builder =>
  407. {
  408. builder
  409. .WithOrigins(
  410. configuration["App:CorsOrigins"]
  411. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  412. .Select(o => o.RemovePostFix("/"))
  413. .ToArray()
  414. )
  415. .WithAbpExposedHeaders()
  416. .SetIsOriginAllowedToAllowWildcardSubdomains()
  417. .AllowAnyHeader()
  418. .AllowAnyMethod()
  419. .AllowCredentials();
  420. });
  421. });
  422. }
  423. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  424. {
  425. var app = context.GetApplicationBuilder();
  426. var configuration = context.GetConfiguration();
  427. app.UseCorrelationId();
  428. app.UseStaticFiles();
  429. app.UseRouting();
  430. app.UseCors(DefaultCorsPolicyName);
  431. app.UseAuthentication();
  432. app.UseAbpClaimsMap();
  433. if (MultiTenancyConsts.IsEnabled)
  434. {
  435. app.UseMultiTenancy();
  436. }
  437. app.UseAbpRequestLocalization();
  438. if (configuration["UseSwagger"] == "true")
  439. {
  440. app.UseSwagger();
  441. app.UseSwaggerUI(options =>
  442. {
  443. options.SwaggerEndpoint("/swagger/v1/swagger.json", "Business Service API");
  444. });
  445. }
  446. app.UseAuditing();
  447. app.UseAbpSerilogEnrichers();
  448. app.UseUnitOfWork();
  449. app.UseConfiguredEndpoints();
  450. app.UseQuartz();
  451. //AsyncHelper.RunSync(async () =>
  452. //{
  453. // using (var scope = context.ServiceProvider.CreateScope())
  454. // {
  455. // await scope.ServiceProvider
  456. // .GetRequiredService<IDataSeeder>()
  457. // .SeedAsync();
  458. // }
  459. //});
  460. }
  461. }
  462. }