using Estsh.Core.Quartz.BaseJobs; using Estsh.Core.Quartz.BaseService; using Estsh.Core.Quartz.EFContext; using Estsh.Core.Quartz.Service; using Estsh.Core.Quartz.Tools; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Impl; using Quartz.Spi; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Estsh.Core.Quartz.Extensions { public static class QuartzUIExtension { public static IServiceCollection AddQuartzUI(this IServiceCollection services, DbContextOptions option = null) { services.AddRazorPages(); services.AddHttpClient(); services.AddHttpContextAccessor(); if (option != null) { services.AddSingleton>(a => { return option; }); services.AddDbContext(); services.AddScoped(); services.AddScoped(); } else { services.AddScoped(); services.AddScoped(); services.AddScoped(); } services.AddScoped(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); return services; } /// /// 自动注入定时任务类 /// /// /// public static IServiceCollection AddQuartzClassJobs(this IServiceCollection services, string assemblyPrefix = "") { var baseType = typeof(IJobService); var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; string[] referencedAssemblies; if (string.IsNullOrEmpty(assemblyPrefix)) { referencedAssemblies = Directory.GetFiles(path, "*.dll"); }else { referencedAssemblies = Directory.GetFiles(path, assemblyPrefix + ".*.dll"); } List typelist = new List(); foreach (var item in referencedAssemblies) { try { var assembly = Assembly.LoadFrom(item); Type[] ts = assembly.GetTypes(); typelist.AddRange(ts.ToList()); } catch (Exception) { continue; } } var types = typelist .Where(x => x != baseType && baseType.IsAssignableFrom(x)).ToArray(); var implementTypes = types.Where(x => x.IsClass).ToArray(); var interfaceTypes = types.Where(x => x.IsInterface).ToArray(); foreach (var implementType in implementTypes) { var interfaceType = implementType.GetInterfaces().First(); services.AddScoped(interfaceType, implementType); ClassJobsFactory.ClassJobs.Add(implementType.Name); } return services; } public static IApplicationBuilder UseQuartz(this IApplicationBuilder builder) { builder.UseRouting(); builder.UseStaticFiles(); builder.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); IServiceProvider services = builder.ApplicationServices; using (var serviceScope = services.CreateScope()) { var dd = serviceScope.ServiceProvider.GetService(); dd.InitJobs(); } return builder; } } }