using Autofac.Core; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WIDESEA_Core.Helper; namespace WIDESEA_Core.Middlewares { /// /// 查看所有注入的服务 /// public static class AllServicesMiddleware { /// /// 注册一个中间件,用于显示所有已注册的服务信息 /// /// 应用程序构建器 /// 服务集合 /// /// 该中间件会在"/allservices"路径下生成一个HTML表格, /// 展示所有注册的服务类型、生命周期和实现类型信息, /// 包括通过Autofac注册的服务 /// public static void UseAllServicesMiddle(this IApplicationBuilder app, IServiceCollection _services) { if (app == null) throw new ArgumentNullException(nameof(app)); //List tsDIAutofac = new List(); //tsDIAutofac.AddRange(Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "Blog.Core.Services.dll")).GetTypes().ToList()); //tsDIAutofac.AddRange(Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "Blog.Core.Repository.dll")).GetTypes().ToList()); IEnumerable autofacContainers = (app.ApplicationServices.GetAutofacRoot())?.ComponentRegistry?.Registrations ?? new List(); app.Map("/allservices", builder => builder.Run(async context => { context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync(""); await context.Response.WriteAsync($"

所有服务{_services.Count}个

"); foreach (var svc in _services) { await context.Response.WriteAsync(""); await context.Response.WriteAsync($""); await context.Response.WriteAsync($""); await context.Response.WriteAsync($""); await context.Response.WriteAsync(""); } foreach (var item in autofacContainers?.ToList()) { var interfaceType = item.Services; foreach (var typeArray in interfaceType) { await context.Response.WriteAsync(""); await context.Response.WriteAsync($""); await context.Response.WriteAsync($""); await context.Response.WriteAsync($""); await context.Response.WriteAsync(""); } } await context.Response.WriteAsync("
类型生命周期Instance
{svc.ServiceType.FullName}{svc.Lifetime}{svc.ImplementationType?.Name}
{typeArray?.Description}{item?.Lifetime}{item?.Target.Activator.ObjToString().Replace("(ReflectionActivator)", "")}
"); })); } } }