BusinessHostModule.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using Autofac.Core;
  2. using Business.Core.MongoDBHelper;
  3. using Business.Core.Utilities;
  4. using Business.EntityFrameworkCore;
  5. using Business.MultiTenancy;
  6. using Business.Quartz;
  7. using Microsoft.AspNetCore.Authentication.JwtBearer;
  8. using Microsoft.AspNetCore.Builder;
  9. using Microsoft.AspNetCore.Cors;
  10. using Microsoft.AspNetCore.DataProtection;
  11. using Microsoft.AspNetCore.Hosting;
  12. using Microsoft.Extensions.Configuration;
  13. using Microsoft.Extensions.DependencyInjection;
  14. using Microsoft.Extensions.Hosting;
  15. using Microsoft.Extensions.Logging;
  16. using Microsoft.OpenApi.Models;
  17. using NLog;
  18. using NLog.Extensions.Logging;
  19. using NLog.Web;
  20. using Quartz;
  21. using Serilog.Events;
  22. using StackExchange.Redis;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.Data;
  26. using System.IO;
  27. using System.Linq;
  28. using Volo.Abp;
  29. using Volo.Abp.AspNetCore.ExceptionHandling;
  30. using Volo.Abp.AspNetCore.MultiTenancy;
  31. using Volo.Abp.AspNetCore.Mvc;
  32. using Volo.Abp.AspNetCore.Serilog;
  33. using Volo.Abp.Autofac;
  34. using Volo.Abp.Caching;
  35. using Volo.Abp.Data;
  36. using Volo.Abp.EntityFrameworkCore.MySQL;
  37. using Volo.Abp.Localization;
  38. using Volo.Abp.Modularity;
  39. using Volo.Abp.MultiTenancy;
  40. using Volo.Abp.Threading;
  41. using Volo.Abp.VirtualFileSystem;
  42. namespace Business
  43. {
  44. [DependsOn(
  45. typeof(AbpAutofacModule),
  46. typeof(AbpEntityFrameworkCoreMySQLModule),
  47. typeof(BusinessHttpApiModule),
  48. typeof(BusinessApplicationModule),
  49. typeof(BusinessEntityFrameworkCoreModule),
  50. typeof(AbpAspNetCoreMultiTenancyModule),
  51. typeof(AbpAspNetCoreSerilogModule)
  52. )]
  53. public class BusinessHostModule : AbpModule
  54. {
  55. private const string DefaultCorsPolicyName = "Default";
  56. public override void ConfigureServices(ServiceConfigurationContext context)
  57. {
  58. var configuration = context.Services.GetConfiguration();
  59. var hostingEnvironment = context.Services.GetHostingEnvironment();
  60. //ConfigureConventionalControllers();
  61. ConfigureMultiTenancy();
  62. ConfigureAuthentication(context, configuration);
  63. ConfigureLocalization();
  64. ConfigureCache(configuration);
  65. ConfigureVirtualFileSystem(context, hostingEnvironment);
  66. //ConfigureRedis(context, configuration, hostingEnvironment);
  67. ConfigureCors(context, configuration);
  68. ConfigureSwaggerServices(context, configuration);
  69. ConfigureQuartz(context, configuration);
  70. //MongoDB依赖注入
  71. ConfigureMongoDB(configuration);
  72. if (hostingEnvironment.IsDevelopment())
  73. {
  74. Configure<AbpExceptionHandlingOptions>(options =>
  75. {
  76. options.SendExceptionsDetailsToClients = true;
  77. });
  78. }
  79. }
  80. private void ConfigureConventionalControllers()
  81. {
  82. Configure<AbpAspNetCoreMvcOptions>(options =>
  83. {
  84. options.ConventionalControllers.Create(typeof(BusinessApplicationModule).Assembly);
  85. });
  86. }
  87. private void ConfigureMultiTenancy()
  88. {
  89. Configure<AbpMultiTenancyOptions>(options =>
  90. {
  91. options.IsEnabled = true;
  92. });
  93. }
  94. private void ConfigureQuartz(ServiceConfigurationContext context, IConfiguration configuration)
  95. {
  96. //程序启动执行一次日志分表检查,可以自己初始化避免需要部署脚本
  97. LogHostedService logHostedService = new LogHostedService();
  98. logHostedService.LogInstall();
  99. context.Services.AddQuartz(q =>
  100. {
  101. q.UseMicrosoftDependencyInjectionScopedJobFactory();
  102. // Just use the name of your job that you created in the Jobs folder.
  103. var jobKey = new JobKey("SyncDataJob");
  104. q.AddJob<SyncMySQLDataJob>(opts => opts.WithIdentity(jobKey));
  105. q.AddTrigger(opts => opts
  106. .ForJob(jobKey)
  107. .WithIdentity("SyncDataJob-trigger")
  108. .WithCronSchedule("0 01 01 * * ?")
  109. .WithDescription("定时同步MySQL基础数据到MongoDB"));
  110. var NLogJobKey = new JobKey("NLogJob");
  111. q.AddJob<NLogJob>(opts => opts.WithIdentity(NLogJobKey));
  112. q.AddTrigger(opts => opts
  113. .ForJob(NLogJobKey)
  114. .WithIdentity("NLogJob-trigger")
  115. .WithCronSchedule("0 01 01 * * ?")
  116. .WithDescription("定时创建NLog日志按月分表"));
  117. var ExtJobKey = new JobKey("ExtJob");
  118. q.AddJob<ExtJob>(opts => opts.WithIdentity(ExtJobKey));
  119. q.AddTrigger(opts => opts
  120. .ForJob(ExtJobKey)
  121. .WithIdentity("ExtJob-trigger")
  122. .WithCronSchedule("0 01 01 * * ?")
  123. .WithDescription("定时处理金蝶同步到Ext数据库的数据"));
  124. //var ProductionScheduleJobKey = new JobKey("ProductionScheduleJob");
  125. //q.AddJob<ProductionScheduleJob>(opts => opts.WithIdentity(ProductionScheduleJobKey));
  126. //q.AddTrigger(opts => opts
  127. // .ForJob(ProductionScheduleJobKey)
  128. // .WithIdentity("ProductionScheduleJob-trigger")
  129. // .WithCronSchedule("0 01 01 * * ?")
  130. // .WithDescription("定时排产任务"));
  131. });
  132. context.Services.AddQuartzServer(options =>
  133. {
  134. // when shutting down we want jobs to complete gracefully
  135. options.WaitForJobsToComplete = true;
  136. });
  137. //context.Services.AddQuartzHostedService(options =>
  138. //{
  139. // // when shutting down we want jobs to complete gracefully
  140. // options.WaitForJobsToComplete = true;
  141. //});
  142. }
  143. /// <summary>
  144. /// MongoDB依赖注入
  145. /// </summary>
  146. /// <param name="context"></param>
  147. /// <param name="configuration"></param>
  148. private void ConfigureMongoDB(IConfiguration configuration)
  149. {
  150. Configure<Config>(options =>
  151. {
  152. options.connectstring = configuration.GetConnectionString("MongoDB");
  153. options.database = configuration.GetConnectionString("DBName");
  154. });
  155. }
  156. private void ConfigureCache(IConfiguration configuration)
  157. {
  158. Configure<AbpDistributedCacheOptions>(options =>
  159. {
  160. options.KeyPrefix = "dopbiz:";
  161. });
  162. }
  163. private void ConfigureVirtualFileSystem(ServiceConfigurationContext context, IWebHostEnvironment webHostEnvironment)
  164. {
  165. //var hostingEnvironment = context.Services.GetHostingEnvironment();
  166. if (webHostEnvironment.IsDevelopment())
  167. {
  168. Configure<AbpVirtualFileSystemOptions>(options =>
  169. {
  170. options.FileSets.ReplaceEmbeddedByPhysical<BusinessDomainModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Domain"));
  171. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationContractsModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application.Contracts"));
  172. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application"));
  173. });
  174. }
  175. }
  176. private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
  177. {
  178. context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  179. .AddJwtBearer(options =>
  180. {
  181. options.Authority = configuration["AuthServer:Authority"];
  182. options.RequireHttpsMetadata = false;
  183. options.Audience = "BusinessService";
  184. });
  185. }
  186. private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
  187. {
  188. if (configuration["UseSwagger"] == "true")
  189. {
  190. context.Services.AddSwaggerGen(options =>
  191. {
  192. options.SwaggerDoc("v1", new OpenApiInfo { Title = "Business Service API", Version = "v1" });
  193. options.DocInclusionPredicate((docName, description) => true);
  194. options.CustomSchemaIds(type => type.FullName);
  195. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  196. {
  197. Description = "请输入JWT令牌,例如:Bearer 12345abcdef",
  198. Name = "Authorization",
  199. In = ParameterLocation.Header,
  200. Type = SecuritySchemeType.ApiKey,
  201. Scheme = "Bearer"
  202. });
  203. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  204. {
  205. {
  206. new OpenApiSecurityScheme
  207. {
  208. Reference = new OpenApiReference
  209. {
  210. Type = ReferenceType.SecurityScheme,
  211. Id = "Bearer"
  212. },
  213. Scheme = "oauth2",
  214. Name = "Bearer",
  215. In = ParameterLocation.Header,
  216. },
  217. new List<string>()
  218. }
  219. });
  220. });
  221. }
  222. }
  223. private void ConfigureLocalization()
  224. {
  225. Configure<AbpLocalizationOptions>(options =>
  226. {
  227. options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
  228. options.Languages.Add(new LanguageInfo("en", "en", "English"));
  229. options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
  230. options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
  231. options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
  232. options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
  233. });
  234. }
  235. private void ConfigureRedis(
  236. ServiceConfigurationContext context,
  237. IConfiguration configuration,
  238. IWebHostEnvironment hostingEnvironment)
  239. {
  240. context.Services.AddStackExchangeRedisCache(options =>
  241. {
  242. options.Configuration = configuration["Redis:Configuration"];
  243. });
  244. if (!hostingEnvironment.IsDevelopment())
  245. {
  246. var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
  247. context.Services
  248. .AddDataProtection()
  249. .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
  250. }
  251. }
  252. private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
  253. {
  254. context.Services.AddCors(options =>
  255. {
  256. options.AddPolicy(DefaultCorsPolicyName, builder =>
  257. {
  258. builder
  259. .WithOrigins(
  260. configuration["App:CorsOrigins"]
  261. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  262. .Select(o => o.RemovePostFix("/"))
  263. .ToArray()
  264. )
  265. .WithAbpExposedHeaders()
  266. .SetIsOriginAllowedToAllowWildcardSubdomains()
  267. .AllowAnyHeader()
  268. .AllowAnyMethod()
  269. .AllowCredentials();
  270. });
  271. });
  272. }
  273. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  274. {
  275. var app = context.GetApplicationBuilder();
  276. var configuration = context.GetConfiguration();
  277. app.UseCorrelationId();
  278. app.UseStaticFiles();
  279. app.UseRouting();
  280. app.UseCors(DefaultCorsPolicyName);
  281. app.UseAuthentication();
  282. app.UseAbpClaimsMap();
  283. if (MultiTenancyConsts.IsEnabled)
  284. {
  285. app.UseMultiTenancy();
  286. }
  287. app.UseAbpRequestLocalization();
  288. if (configuration["UseSwagger"] == "true")
  289. {
  290. app.UseSwagger();
  291. app.UseSwaggerUI(options =>
  292. {
  293. options.SwaggerEndpoint("/swagger/v1/swagger.json", "Business Service API");
  294. });
  295. }
  296. app.UseAuditing();
  297. app.UseAbpSerilogEnrichers();
  298. app.UseUnitOfWork();
  299. app.UseConfiguredEndpoints();
  300. AsyncHelper.RunSync(async () =>
  301. {
  302. using (var scope = context.ServiceProvider.CreateScope())
  303. {
  304. await scope.ServiceProvider
  305. .GetRequiredService<IDataSeeder>()
  306. .SeedAsync();
  307. }
  308. });
  309. }
  310. }
  311. }