66 lines
2.4 KiB
C#
66 lines
2.4 KiB
C#
using System.Reflection;
|
|
|
|
namespace LFlow.Middleware.Register
|
|
{
|
|
public static class MiddlewareRegister
|
|
{
|
|
private static IServiceProvider? _serviceProvider;
|
|
|
|
private static readonly IDictionary<Type, ILFlowMiddleware> _middlewares = new Dictionary<Type, ILFlowMiddleware>();
|
|
private static List<Type> _middlewareTypes = [];
|
|
public static void RegisterMiddlewares(this IServiceCollection service, List<Assembly> assemblies)
|
|
{
|
|
if (assemblies == null || assemblies.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
// 列入系统内置中间件
|
|
var allAssemblies = new List<Assembly>(assemblies)
|
|
{
|
|
Assembly.GetAssembly(typeof(ILFlowMiddleware))!
|
|
};
|
|
|
|
allAssemblies.ForEach(assembly =>
|
|
{
|
|
var types = assembly.GetTypes().ToList();
|
|
foreach (var type in types)
|
|
{
|
|
if (type.GetInterface(nameof(ILFlowMiddleware)) != null)
|
|
{
|
|
service.AddSingleton(type);
|
|
_middlewareTypes.Add(type);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
public static void BuildMiddlewareServiceProvider(this IApplicationBuilder application)
|
|
{
|
|
_serviceProvider = application.ApplicationServices;
|
|
_middlewareTypes.ForEach(type =>
|
|
{
|
|
if (_serviceProvider.GetService(type) is ILFlowMiddleware middleware)
|
|
_middlewares.Add(type, middleware);
|
|
});
|
|
}
|
|
/// <summary>
|
|
/// 处理中间件
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
/// <param name="next"></param>
|
|
/// <returns></returns>
|
|
public static async Task Handle(IApplicationBuilder application)
|
|
{
|
|
//var logger = application.ApplicationServices.GetService<ILogger>();
|
|
var orderedMiddlewares = _middlewares.Values.OrderBy(m => m.Priority).ToList();
|
|
foreach (var middleware in orderedMiddlewares)
|
|
{
|
|
await Task.FromResult(application.Use(middleware.RunAsync));
|
|
//logger?.LogInformation("Middleware {MiddlewareName} is registered.", middleware.GetType().Name);
|
|
Console.WriteLine($"[{DateTime.Now:hh:mm:ss} INF] Middleware {middleware.GetType().Name} is registered.");
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|