| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- using Autofac.Core;
- using Business.Core.MongoDBHelper;
- using Business.Core.Utilities;
- using Business.EntityFrameworkCore;
- using Business.MultiTenancy;
- using Business.Quartz;
- using GZY.Quartz.MUI.EFContext;
- using GZY.Quartz.MUI.Extensions;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Cors;
- using Microsoft.AspNetCore.DataProtection;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using NLog;
- using NLog.Extensions.Logging;
- using NLog.Web;
- using Quartz;
- using Serilog.Events;
- using StackExchange.Redis;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Linq;
- using Volo.Abp;
- using Volo.Abp.AspNetCore.ExceptionHandling;
- using Volo.Abp.AspNetCore.MultiTenancy;
- using Volo.Abp.AspNetCore.Mvc;
- using Volo.Abp.AspNetCore.Serilog;
- using Volo.Abp.Autofac;
- using Volo.Abp.Caching;
- using Volo.Abp.Data;
- using Volo.Abp.EntityFrameworkCore.MySQL;
- using Volo.Abp.Localization;
- using Volo.Abp.Modularity;
- using Volo.Abp.MultiTenancy;
- using Volo.Abp.Threading;
- using Volo.Abp.VirtualFileSystem;
- using Bussiness.MongoDB;
- namespace Business
- {
- [DependsOn(
- typeof(AbpAutofacModule),
- typeof(AbpEntityFrameworkCoreMySQLModule),
- typeof(BusinessHttpApiModule),
- typeof(BusinessApplicationModule),
- typeof(BusinessEntityFrameworkCoreModule),
- typeof(BussinessMongoDbModule),
- typeof(AbpAspNetCoreMultiTenancyModule),
- typeof(AbpAspNetCoreSerilogModule)
- )]
- public class BusinessHostModule : AbpModule
- {
- private const string DefaultCorsPolicyName = "Default";
- public override void ConfigureServices(ServiceConfigurationContext context)
- {
- var configuration = context.Services.GetConfiguration();
- var hostingEnvironment = context.Services.GetHostingEnvironment();
- //ConfigureConventionalControllers();
- ConfigureMultiTenancy();
- ConfigureAuthentication(context, configuration);
- ConfigureLocalization();
- ConfigureCache(configuration);
- ConfigureVirtualFileSystem(context, hostingEnvironment);
- //ConfigureRedis(context, configuration, hostingEnvironment);
- ConfigureCors(context, configuration);
- ConfigureSwaggerServices(context, configuration);
- ConfigureQuartz(context, configuration);
- //MongoDB依赖注入
- ConfigureMongoDB(configuration);
- if (hostingEnvironment.IsDevelopment())
- {
- Configure<AbpExceptionHandlingOptions>(options =>
- {
- options.SendExceptionsDetailsToClients = true;
- });
- }
- }
- private void ConfigureConventionalControllers()
- {
- Configure<AbpAspNetCoreMvcOptions>(options =>
- {
- options.ConventionalControllers.Create(typeof(BusinessApplicationModule).Assembly);
- });
- }
- private void ConfigureMultiTenancy()
- {
- Configure<AbpMultiTenancyOptions>(options =>
- {
- options.IsEnabled = true;
- });
- }
- private void ConfigureQuartz(ServiceConfigurationContext context, IConfiguration configuration)
- {
- //程序启动执行一次日志分表检查,可以自己初始化避免需要部署脚本
- LogHostedService logHostedService = new LogHostedService();
- logHostedService.LogInstall();
- context.Services.AddQuartz(q =>
- {
- q.UseMicrosoftDependencyInjectionScopedJobFactory();
- // Just use the name of your job that you created in the Jobs folder.
- var jobKey = new JobKey("SyncDataJob");
- q.AddJob<SyncMySQLDataJob>(opts => opts.WithIdentity(jobKey));
- q.AddTrigger(opts => opts
- .ForJob(jobKey)
- .WithIdentity("SyncDataJob-trigger")
- .WithCronSchedule("0 38 10 * * ?")
- .WithDescription("定时同步MySQL基础数据到MongoDB"));
- var NLogJobKey = new JobKey("NLogJob");
- q.AddJob<NLogJob>(opts => opts.WithIdentity(NLogJobKey));
- q.AddTrigger(opts => opts
- .ForJob(NLogJobKey)
- .WithIdentity("NLogJob-trigger")
- .WithCronSchedule("0 01 01 * * ?")
- .WithDescription("定时创建NLog日志按月分表"));
- //var ExtJobKey = new JobKey("ExtJob");
- //q.AddJob<ExtJob>(opts => opts.WithIdentity(ExtJobKey));
- //q.AddTrigger(opts => opts
- // .ForJob(ExtJobKey)
- // .WithIdentity("ExtJob-trigger")
- // .WithCronSchedule("0 01 01 * * ?")
- // .WithDescription("定时处理金蝶同步到Ext数据库的数据"));
- var WMSJobKey = new JobKey("WMSJob");
- q.AddJob<WMSJob>(opts => opts.WithIdentity(WMSJobKey));
- q.AddTrigger(opts => opts
- .ForJob(WMSJobKey)
- .WithIdentity("WMSJob-trigger")
- .WithCronSchedule("0 32 15 * * ?")
- .WithDescription("定时同步WMS物料订单等基础数据到MySQL"));
- //var ProductionScheduleJobKey = new JobKey("ProductionScheduleJob");
- //q.AddJob<ProductionScheduleJob>(opts => opts.WithIdentity(ProductionScheduleJobKey));
- //q.AddTrigger(opts => opts
- // .ForJob(ProductionScheduleJobKey)
- // .WithIdentity("ProductionScheduleJob-trigger")
- // .WithCronSchedule("0 01 01 * * ?")
- // .WithDescription("定时排产任务"));
- });
- context.Services.AddQuartzServer(options =>
- {
- // when shutting down we want jobs to complete gracefully
- options.WaitForJobsToComplete = true;
- });
- context.Services.AddQuartzUI();
- context.Services.AddQuartzClassJobs(); //添加本地调度任务访问
- context.Services.AddQuartzHostedService(options =>
- {
- // when shutting down we want jobs to complete gracefully
- options.WaitForJobsToComplete = true;
- });
- }
- /// <summary>
- /// MongoDB依赖注入
- /// </summary>
- /// <param name="context"></param>
- /// <param name="configuration"></param>
- private void ConfigureMongoDB(IConfiguration configuration)
- {
- Configure<Config>(options =>
- {
- options.connectstring = configuration.GetConnectionString("MongoDB");
- options.database = configuration.GetConnectionString("DBName");
- });
- }
- private void ConfigureCache(IConfiguration configuration)
- {
- Configure<AbpDistributedCacheOptions>(options =>
- {
- options.KeyPrefix = "dopbiz:";
- });
- }
- private void ConfigureVirtualFileSystem(ServiceConfigurationContext context, IWebHostEnvironment webHostEnvironment)
- {
- //var hostingEnvironment = context.Services.GetHostingEnvironment();
- if (webHostEnvironment.IsDevelopment())
- {
- Configure<AbpVirtualFileSystemOptions>(options =>
- {
- options.FileSets.ReplaceEmbeddedByPhysical<BusinessDomainModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Domain"));
- options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationContractsModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application.Contracts"));
- options.FileSets.ReplaceEmbeddedByPhysical<BusinessApplicationModule>(Path.Combine(webHostEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Business.Application"));
- });
- }
- }
- private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
- {
- context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.Authority = configuration["AuthServer:Authority"];
- options.RequireHttpsMetadata = false;
- options.Audience = "BusinessService";
- });
- }
- private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
- {
- if (configuration["UseSwagger"] == "true")
- {
- context.Services.AddSwaggerGen(options =>
- {
- options.SwaggerDoc("v1", new OpenApiInfo { Title = "Business Service API", Version = "v1" });
- options.DocInclusionPredicate((docName, description) => true);
- options.CustomSchemaIds(type => type.FullName);
- options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
- {
- Description = "请输入JWT令牌,例如:Bearer 12345abcdef",
- Name = "Authorization",
- In = ParameterLocation.Header,
- Type = SecuritySchemeType.ApiKey,
- Scheme = "Bearer"
- });
- options.AddSecurityRequirement(new OpenApiSecurityRequirement()
- {
- {
- new OpenApiSecurityScheme
- {
- Reference = new OpenApiReference
- {
- Type = ReferenceType.SecurityScheme,
- Id = "Bearer"
- },
- Scheme = "oauth2",
- Name = "Bearer",
- In = ParameterLocation.Header,
- },
- new List<string>()
- }
- });
- });
- }
- }
- private void ConfigureLocalization()
- {
- Configure<AbpLocalizationOptions>(options =>
- {
- options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
- options.Languages.Add(new LanguageInfo("en", "en", "English"));
- options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
- options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
- options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
- options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
- });
- }
- private void ConfigureRedis(
- ServiceConfigurationContext context,
- IConfiguration configuration,
- IWebHostEnvironment hostingEnvironment)
- {
- context.Services.AddStackExchangeRedisCache(options =>
- {
- options.Configuration = configuration["Redis:Configuration"];
- });
- if (!hostingEnvironment.IsDevelopment())
- {
- var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
- context.Services
- .AddDataProtection()
- .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
- }
- }
- private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
- {
- context.Services.AddCors(options =>
- {
- options.AddPolicy(DefaultCorsPolicyName, builder =>
- {
- builder
- .WithOrigins(
- configuration["App:CorsOrigins"]
- .Split(",", StringSplitOptions.RemoveEmptyEntries)
- .Select(o => o.RemovePostFix("/"))
- .ToArray()
- )
- .WithAbpExposedHeaders()
- .SetIsOriginAllowedToAllowWildcardSubdomains()
- .AllowAnyHeader()
- .AllowAnyMethod()
- .AllowCredentials();
- });
- });
- }
- public override void OnApplicationInitialization(ApplicationInitializationContext context)
- {
- var app = context.GetApplicationBuilder();
- var configuration = context.GetConfiguration();
- app.UseCorrelationId();
- app.UseStaticFiles();
- app.UseRouting();
- app.UseCors(DefaultCorsPolicyName);
- app.UseAuthentication();
- app.UseAbpClaimsMap();
- if (MultiTenancyConsts.IsEnabled)
- {
- app.UseMultiTenancy();
- }
- app.UseAbpRequestLocalization();
- if (configuration["UseSwagger"] == "true")
- {
- app.UseSwagger();
- app.UseSwaggerUI(options =>
- {
- options.SwaggerEndpoint("/swagger/v1/swagger.json", "Business Service API");
- });
- }
- app.UseAuditing();
- app.UseAbpSerilogEnrichers();
- app.UseUnitOfWork();
- app.UseConfiguredEndpoints();
- app.UseQuartz();
- //AsyncHelper.RunSync(async () =>
- //{
- // using (var scope = context.ServiceProvider.CreateScope())
- // {
- // await scope.ServiceProvider
- // .GetRequiredService<IDataSeeder>()
- // .SeedAsync();
- // }
- //});
- }
- }
- }
|