BusinessHostModule.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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("DemoJob-trigger")
  108. .WithCronSchedule("0 45 11 * * ?")
  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("DemoJob-trigger")
  115. .WithCronSchedule("0 0 0 * * ?")
  116. .WithDescription("定时创建NLog日志按月分表"));
  117. });
  118. context.Services.AddQuartzServer(options =>
  119. {
  120. // when shutting down we want jobs to complete gracefully
  121. options.WaitForJobsToComplete = true;
  122. });
  123. //context.Services.AddQuartzHostedService(options =>
  124. //{
  125. // // when shutting down we want jobs to complete gracefully
  126. // options.WaitForJobsToComplete = true;
  127. //});
  128. }
  129. /// <summary>
  130. /// MongoDB依赖注入
  131. /// </summary>
  132. /// <param name="context"></param>
  133. /// <param name="configuration"></param>
  134. private void ConfigureMongoDB(IConfiguration configuration)
  135. {
  136. Configure<Config>(options =>
  137. {
  138. options.connectstring = configuration.GetConnectionString("MongoDB");
  139. options.database = configuration.GetConnectionString("DBName");
  140. });
  141. }
  142. private void ConfigureCache(IConfiguration configuration)
  143. {
  144. Configure<AbpDistributedCacheOptions>(options =>
  145. {
  146. options.KeyPrefix = "dopbiz:";
  147. });
  148. }
  149. private void ConfigureVirtualFileSystem(ServiceConfigurationContext context, IWebHostEnvironment webHostEnvironment)
  150. {
  151. //var hostingEnvironment = context.Services.GetHostingEnvironment();
  152. if (webHostEnvironment.IsDevelopment())
  153. {
  154. Configure<AbpVirtualFileSystemOptions>(options =>
  155. {
  156. options.FileSets.ReplaceEmbeddedByPhysical<BusinessDomainModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Domain"));
  157. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationContractsModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application.Contracts"));
  158. options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application"));
  159. });
  160. }
  161. }
  162. private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
  163. {
  164. context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  165. .AddJwtBearer(options =>
  166. {
  167. options.Authority = configuration["AuthServer:Authority"];
  168. options.RequireHttpsMetadata = false;
  169. options.Audience = "BusinessService";
  170. });
  171. }
  172. private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
  173. {
  174. if (configuration["UseSwagger"] == "true")
  175. {
  176. context.Services.AddSwaggerGen(options =>
  177. {
  178. options.SwaggerDoc("v1", new OpenApiInfo { Title = "Business Service API", Version = "v1" });
  179. options.DocInclusionPredicate((docName, description) => true);
  180. options.CustomSchemaIds(type => type.FullName);
  181. options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  182. {
  183. Description = "请输入JWT令牌,例如:Bearer 12345abcdef",
  184. Name = "Authorization",
  185. In = ParameterLocation.Header,
  186. Type = SecuritySchemeType.ApiKey,
  187. Scheme = "Bearer"
  188. });
  189. options.AddSecurityRequirement(new OpenApiSecurityRequirement()
  190. {
  191. {
  192. new OpenApiSecurityScheme
  193. {
  194. Reference = new OpenApiReference
  195. {
  196. Type = ReferenceType.SecurityScheme,
  197. Id = "Bearer"
  198. },
  199. Scheme = "oauth2",
  200. Name = "Bearer",
  201. In = ParameterLocation.Header,
  202. },
  203. new List<string>()
  204. }
  205. });
  206. });
  207. }
  208. }
  209. private void ConfigureLocalization()
  210. {
  211. Configure<AbpLocalizationOptions>(options =>
  212. {
  213. options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
  214. options.Languages.Add(new LanguageInfo("en", "en", "English"));
  215. options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
  216. options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
  217. options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
  218. options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
  219. });
  220. }
  221. private void ConfigureRedis(
  222. ServiceConfigurationContext context,
  223. IConfiguration configuration,
  224. IWebHostEnvironment hostingEnvironment)
  225. {
  226. context.Services.AddStackExchangeRedisCache(options =>
  227. {
  228. options.Configuration = configuration["Redis:Configuration"];
  229. });
  230. if (!hostingEnvironment.IsDevelopment())
  231. {
  232. var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
  233. context.Services
  234. .AddDataProtection()
  235. .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
  236. }
  237. }
  238. private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
  239. {
  240. context.Services.AddCors(options =>
  241. {
  242. options.AddPolicy(DefaultCorsPolicyName, builder =>
  243. {
  244. builder
  245. .WithOrigins(
  246. configuration["App:CorsOrigins"]
  247. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  248. .Select(o => o.RemovePostFix("/"))
  249. .ToArray()
  250. )
  251. .WithAbpExposedHeaders()
  252. .SetIsOriginAllowedToAllowWildcardSubdomains()
  253. .AllowAnyHeader()
  254. .AllowAnyMethod()
  255. .AllowCredentials();
  256. });
  257. });
  258. }
  259. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  260. {
  261. var app = context.GetApplicationBuilder();
  262. var configuration = context.GetConfiguration();
  263. app.UseCorrelationId();
  264. app.UseStaticFiles();
  265. app.UseRouting();
  266. app.UseCors(DefaultCorsPolicyName);
  267. app.UseAuthentication();
  268. app.UseAbpClaimsMap();
  269. if (MultiTenancyConsts.IsEnabled)
  270. {
  271. app.UseMultiTenancy();
  272. }
  273. app.UseAbpRequestLocalization();
  274. if (configuration["UseSwagger"] == "true")
  275. {
  276. app.UseSwagger();
  277. app.UseSwaggerUI(options =>
  278. {
  279. options.SwaggerEndpoint("/swagger/v1/swagger.json", "Business Service API");
  280. });
  281. }
  282. app.UseAuditing();
  283. app.UseAbpSerilogEnrichers();
  284. app.UseUnitOfWork();
  285. app.UseConfiguredEndpoints();
  286. AsyncHelper.RunSync(async () =>
  287. {
  288. using (var scope = context.ServiceProvider.CreateScope())
  289. {
  290. await scope.ServiceProvider
  291. .GetRequiredService<IDataSeeder>()
  292. .SeedAsync();
  293. }
  294. });
  295. }
  296. }
  297. }