ASP.NET Core 中间件(Middleware)的使用及其源码解析(二)- 使用UseMiddle ...

打印 上一主题 下一主题

主题 893|帖子 893|积分 2679

有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件。除了直接用 ApplicationBuilder 的 Use() 方法注册中间件外,还可以使用 ApplicationBuilder 的扩展方法 UseMiddleware() 注册自定义中间件。
废话不多说,我们在上一篇的基础上加一个自定义中间件类 CustomMiddleware ,如下所示:
  1. using Microsoft.AspNetCore.Http;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace NETCoreMiddleware.Middlewares
  7. {
  8.     /// <summary>
  9.     /// 自定义中间件
  10.     /// </summary>
  11.     public class CustomMiddleware
  12.     {
  13.         /// <summary>
  14.         /// 保存下一个中间件
  15.         /// </summary>
  16.         private readonly RequestDelegate _next;
  17.         /// <summary>
  18.         /// 构造函数
  19.         /// </summary>
  20.         /// <param name="next">下一个中间件</param>
  21.         public CustomMiddleware(RequestDelegate next)
  22.         {
  23.             Console.WriteLine($"{typeof(CustomMiddleware)} 被构造");
  24.             _next = next;
  25.         }
  26.         /// <summary>
  27.         /// 中间件方法
  28.         /// </summary>
  29.         public async Task InvokeAsync(HttpContext context)
  30.         {
  31.             await Task.Run(() => Console.WriteLine($"This is CustomMiddleware Start"));
  32.             await _next.Invoke(context); //可通过不调用 next 参数使请求管道短路
  33.             await Task.Run(() => Console.WriteLine($"This is CustomMiddleware End"));
  34.         }
  35.     }
  36. }
复制代码
接着将该中间件装配到我们的Http请求处理管道中,如下所示(标红部分):
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Hosting;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. using NETCoreMiddleware.Middlewares;
  11. namespace NETCoreMiddleware
  12. {
  13.     public class Startup
  14.     {
  15.         public Startup(IConfiguration configuration)
  16.         {
  17.             Configuration = configuration;
  18.         }
  19.         public IConfiguration Configuration { get; }
  20.         //服务注册(往容器中添加服务)
  21.         // This method gets called by the runtime. Use this method to add services to the container.
  22.         public void ConfigureServices(IServiceCollection services)
  23.         {
  24.             services.AddControllersWithViews();
  25.         }
  26.         /// <summary>
  27.         /// 配置Http请求处理管道
  28.         /// Http请求管道模型---就是Http请求被处理的步骤
  29.         /// 所谓管道,就是拿着HttpContext,经过多个步骤的加工,生成Response,这就是管道
  30.         /// </summary>
  31.         /// <param name="app"></param>
  32.         /// <param name="env"></param>
  33.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  34.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  35.         {
  36.             #region 环境参数
  37.             if (env.IsDevelopment())
  38.             {
  39.                 app.UseDeveloperExceptionPage();
  40.             }
  41.             else
  42.             {
  43.                 app.UseExceptionHandler("/Home/Error");
  44.             }
  45.             #endregion 环境参数
  46.             //静态文件中间件
  47.             app.UseStaticFiles();
  48.             #region Use中间件
  49.             //中间件1
  50.             app.Use(next =>
  51.             {
  52.                 Console.WriteLine("middleware 1");
  53.                 return async context =>
  54.                 {
  55.                     await Task.Run(() =>
  56.                     {
  57.                         Console.WriteLine("");
  58.                         Console.WriteLine("===================================Middleware===================================");
  59.                         Console.WriteLine($"This is middleware 1 Start");
  60.                     });
  61.                     await next.Invoke(context);
  62.                     await Task.Run(() =>
  63.                     {
  64.                         Console.WriteLine($"This is middleware 1 End");
  65.                         Console.WriteLine("===================================Middleware===================================");
  66.                     });
  67.                 };
  68.             });
  69.             //中间件2
  70.             app.Use(next =>
  71.             {
  72.                 Console.WriteLine("middleware 2");
  73.                 return async context =>
  74.                 {
  75.                     await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
  76.                     await next.Invoke(context); //可通过不调用 next 参数使请求管道短路
  77.                     await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
  78.                 };
  79.             });
  80.             //中间件3
  81.             app.Use(next =>
  82.             {
  83.                 Console.WriteLine("middleware 3");
  84.                 return async context =>
  85.                 {
  86.                     await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
  87.                     await next.Invoke(context);
  88.                     await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
  89.                 };
  90.             });
  91.             //中间件4
  92.             //Use方法的另外一个重载
  93.             app.Use(async (context, next) =>
  94.             {
  95.                 await Task.Run(() => Console.WriteLine($"This is middleware 4 Start"));
  96.                 await next();
  97.                 await Task.Run(() => Console.WriteLine($"This is middleware 4 End"));
  98.             });
  99.             #endregion Use中间件
  100.             #region UseMiddleware中间件
  101.             app.UseMiddleware<CustomMiddleware>();
  102.             #endregion UseMiddleware中间件
  103.             #region 终端中间件
  104.             //app.Use(_ => handler);
  105.             app.Run(async context =>
  106.             {
  107.                 await Task.Run(() => Console.WriteLine($"This is Run"));
  108.             });
  109.             #endregion 终端中间件
  110.             #region 最终把请求交给MVC
  111.             app.UseRouting();
  112.             app.UseAuthorization();
  113.             app.UseEndpoints(endpoints =>
  114.             {
  115.                 endpoints.MapControllerRoute(
  116.                     name: "areas",
  117.                     pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
  118.                 endpoints.MapControllerRoute(
  119.                     name: "default",
  120.                     pattern: "{controller=Home}/{action=Index}/{id?}");
  121.             });
  122.             #endregion 最终把请求交给MVC
  123.         }
  124.     }
  125. }
复制代码
下面我们使用命令行(CLI)方式启动我们的网站,如下所示:

启动成功后,我们来访问一下 “/home/index” ,控制台输出结果如下所示:

可以发现我们自定义的中间件生效了。
 
下面我们结合ASP.NET Core源码来分析下其实现原理: 
我们将光标移动到 UseMiddleware 处按 F12 转到定义,如下所示:


可以发现它是位于 UseMiddlewareExtensions 扩展类中的,我们找到 UseMiddlewareExtensions 类的源码,如下所示:
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Http.Abstractions;
  10. using Microsoft.Extensions.Internal;
  11. namespace Microsoft.AspNetCore.Builder
  12. {
  13.     /// <summary>
  14.     /// Extension methods for adding typed middleware.
  15.     /// </summary>
  16.     public static class UseMiddlewareExtensions
  17.     {
  18.         internal const string InvokeMethodName = "Invoke";
  19.         internal const string InvokeAsyncMethodName = "InvokeAsync";
  20.         private static readonly MethodInfo GetServiceInfo = typeof(UseMiddlewareExtensions).GetMethod(nameof(GetService), BindingFlags.NonPublic | BindingFlags.Static);
  21.         /// <summary>
  22.         /// Adds a middleware type to the application's request pipeline.
  23.         /// </summary>
  24.         /// <typeparam name="TMiddleware">The middleware type.</typeparam>
  25.         /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
  26.         /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param>
  27.         /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
  28.         public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app, params object[] args)
  29.         {
  30.             return app.UseMiddleware(typeof(TMiddleware), args);
  31.         }
  32.         /// <summary>
  33.         /// Adds a middleware type to the application's request pipeline.
  34.         /// </summary>
  35.         /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
  36.         /// <param name="middleware">The middleware type.</param>
  37.         /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param>
  38.         /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
  39.         public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args)
  40.         {
  41.             if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo()))
  42.             {
  43.                 // IMiddleware doesn't support passing args directly since it's
  44.                 // activated from the container
  45.                 if (args.Length > 0)
  46.                 {
  47.                     throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware)));
  48.                 }
  49.                 return UseMiddlewareInterface(app, middleware);
  50.             }
  51.             var applicationServices = app.ApplicationServices;
  52.             return app.Use(next =>
  53.             {
  54.                 var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public);
  55.                 var invokeMethods = methods.Where(m =>
  56.                     string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)
  57.                     || string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal)
  58.                     ).ToArray();
  59.                 if (invokeMethods.Length > 1)
  60.                 {
  61.                     throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName));
  62.                 }
  63.                 if (invokeMethods.Length == 0)
  64.                 {
  65.                     throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName, middleware));
  66.                 }
  67.                 var methodInfo = invokeMethods[0];
  68.                 if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
  69.                 {
  70.                     throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, InvokeAsyncMethodName, nameof(Task)));
  71.                 }
  72.                 var parameters = methodInfo.GetParameters();
  73.                 if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext))
  74.                 {
  75.                     throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName, nameof(HttpContext)));
  76.                 }
  77.                 var ctorArgs = new object[args.Length + 1];
  78.                 ctorArgs[0] = next;
  79.                 Array.Copy(args, 0, ctorArgs, 1, args.Length);
  80.                 var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middleware, ctorArgs);
  81.                 if (parameters.Length == 1)
  82.                 {
  83.                     return (RequestDelegate)methodInfo.CreateDelegate(typeof(RequestDelegate), instance);
  84.                 }
  85.                 var factory = Compile<object>(methodInfo, parameters);
  86.                 return context =>
  87.                 {
  88.                     var serviceProvider = context.RequestServices ?? applicationServices;
  89.                     if (serviceProvider == null)
  90.                     {
  91.                         throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider)));
  92.                     }
  93.                     return factory(instance, context, serviceProvider);
  94.                 };
  95.             });
  96.         }
  97.         private static IApplicationBuilder UseMiddlewareInterface(IApplicationBuilder app, Type middlewareType)
  98.         {
  99.             return app.Use(next =>
  100.             {
  101.                 return async context =>
  102.                 {
  103.                     var middlewareFactory = (IMiddlewareFactory)context.RequestServices.GetService(typeof(IMiddlewareFactory));
  104.                     if (middlewareFactory == null)
  105.                     {
  106.                         // No middleware factory
  107.                         throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoMiddlewareFactory(typeof(IMiddlewareFactory)));
  108.                     }
  109.                     var middleware = middlewareFactory.Create(middlewareType);
  110.                     if (middleware == null)
  111.                     {
  112.                         // The factory returned null, it's a broken implementation
  113.                         throw new InvalidOperationException(Resources.FormatException_UseMiddlewareUnableToCreateMiddleware(middlewareFactory.GetType(), middlewareType));
  114.                     }
  115.                     try
  116.                     {
  117.                         await middleware.InvokeAsync(context, next);
  118.                     }
  119.                     finally
  120.                     {
  121.                         middlewareFactory.Release(middleware);
  122.                     }
  123.                 };
  124.             });
  125.         }
  126.         private static Func<T, HttpContext, IServiceProvider, Task> Compile<T>(MethodInfo methodInfo, ParameterInfo[] parameters)
  127.         {
  128.             // If we call something like
  129.             //
  130.             // public class Middleware
  131.             // {
  132.             //    public Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
  133.             //    {
  134.             //
  135.             //    }
  136.             // }
  137.             //
  138.             // We'll end up with something like this:
  139.             //   Generic version:
  140.             //
  141.             //   Task Invoke(Middleware instance, HttpContext httpContext, IServiceProvider provider)
  142.             //   {
  143.             //      return instance.Invoke(httpContext, (ILoggerFactory)UseMiddlewareExtensions.GetService(provider, typeof(ILoggerFactory));
  144.             //   }
  145.             //   Non generic version:
  146.             //
  147.             //   Task Invoke(object instance, HttpContext httpContext, IServiceProvider provider)
  148.             //   {
  149.             //      return ((Middleware)instance).Invoke(httpContext, (ILoggerFactory)UseMiddlewareExtensions.GetService(provider, typeof(ILoggerFactory));
  150.             //   }
  151.             var middleware = typeof(T);
  152.             var httpContextArg = Expression.Parameter(typeof(HttpContext), "httpContext");
  153.             var providerArg = Expression.Parameter(typeof(IServiceProvider), "serviceProvider");
  154.             var instanceArg = Expression.Parameter(middleware, "middleware");
  155.             var methodArguments = new Expression[parameters.Length];
  156.             methodArguments[0] = httpContextArg;
  157.             for (int i = 1; i < parameters.Length; i++)
  158.             {
  159.                 var parameterType = parameters[i].ParameterType;
  160.                 if (parameterType.IsByRef)
  161.                 {
  162.                     throw new NotSupportedException(Resources.FormatException_InvokeDoesNotSupportRefOrOutParams(InvokeMethodName));
  163.                 }
  164.                 var parameterTypeExpression = new Expression[]
  165.                 {
  166.                     providerArg,
  167.                     Expression.Constant(parameterType, typeof(Type)),
  168.                     Expression.Constant(methodInfo.DeclaringType, typeof(Type))
  169.                 };
  170.                 var getServiceCall = Expression.Call(GetServiceInfo, parameterTypeExpression);
  171.                 methodArguments[i] = Expression.Convert(getServiceCall, parameterType);
  172.             }
  173.             Expression middlewareInstanceArg = instanceArg;
  174.             if (methodInfo.DeclaringType != typeof(T))
  175.             {
  176.                 middlewareInstanceArg = Expression.Convert(middlewareInstanceArg, methodInfo.DeclaringType);
  177.             }
  178.             var body = Expression.Call(middlewareInstanceArg, methodInfo, methodArguments);
  179.             var lambda = Expression.Lambda<Func<T, HttpContext, IServiceProvider, Task>>(body, instanceArg, httpContextArg, providerArg);
  180.             return lambda.Compile();
  181.         }
  182.         private static object GetService(IServiceProvider sp, Type type, Type middleware)
  183.         {
  184.             var service = sp.GetService(type);
  185.             if (service == null)
  186.             {
  187.                 throw new InvalidOperationException(Resources.FormatException_InvokeMiddlewareNoService(type, middleware));
  188.             }
  189.             return service;
  190.         }
  191.     }
  192. }
复制代码
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions类源码从中我们可以知道,它最终会调用下面的这个方法:
  1. /// <summary>
  2. /// Adds a middleware type to the application's request pipeline.
  3. /// </summary>
  4. /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
  5. /// <param name="middleware">The middleware type.</param>
  6. /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param>
  7. /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
  8. public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args)
  9. {
  10.     if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo()))
  11.     {
  12.         // IMiddleware doesn't support passing args directly since it's
  13.         // activated from the container
  14.         if (args.Length > 0)
  15.         {
  16.             throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware)));
  17.         }
  18.         return UseMiddlewareInterface(app, middleware);
  19.     }
  20.     var applicationServices = app.ApplicationServices;
  21.     return app.Use(next =>
  22.     {
  23.         var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public);
  24.         var invokeMethods = methods.Where(m =>
  25.             string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)
  26.             || string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal)
  27.             ).ToArray();
  28.         if (invokeMethods.Length > 1)
  29.         {
  30.             throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName));
  31.         }
  32.         if (invokeMethods.Length == 0)
  33.         {
  34.             throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName, middleware));
  35.         }
  36.         var methodInfo = invokeMethods[0];
  37.         if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
  38.         {
  39.             throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, InvokeAsyncMethodName, nameof(Task)));
  40.         }
  41.         var parameters = methodInfo.GetParameters();
  42.         if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext))
  43.         {
  44.             throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName, nameof(HttpContext)));
  45.         }
  46.         var ctorArgs = new object[args.Length + 1];
  47.         ctorArgs[0] = next;
  48.         Array.Copy(args, 0, ctorArgs, 1, args.Length);
  49.         var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middleware, ctorArgs);
  50.         if (parameters.Length == 1)
  51.         {
  52.             return (RequestDelegate)methodInfo.CreateDelegate(typeof(RequestDelegate), instance);
  53.         }
  54.         var factory = Compile<object>(methodInfo, parameters);
  55.         return context =>
  56.         {
  57.             var serviceProvider = context.RequestServices ?? applicationServices;
  58.             if (serviceProvider == null)
  59.             {
  60.                 throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider)));
  61.             }
  62.             return factory(instance, context, serviceProvider);
  63.         };
  64.     });
  65. }
复制代码
其中 ActivatorUtilities 类的源码如下:
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Runtime.ExceptionServices;
  8. #if ActivatorUtilities_In_DependencyInjection
  9. using Microsoft.Extensions.Internal;
  10. namespace Microsoft.Extensions.DependencyInjection
  11. #else
  12. namespace Microsoft.Extensions.Internal
  13. #endif
  14. {
  15.     /// <summary>
  16.     /// Helper code for the various activator services.
  17.     /// </summary>
  18. #if ActivatorUtilities_In_DependencyInjection
  19.     public
  20. #else
  21.     // Do not take a dependency on this class unless you are explicitly trying to avoid taking a
  22.     // dependency on Microsoft.AspNetCore.DependencyInjection.Abstractions.
  23.     internal
  24. #endif
  25.     static class ActivatorUtilities
  26.     {
  27.         private static readonly MethodInfo GetServiceInfo =
  28.             GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object>>((sp, t, r, c) => GetService(sp, t, r, c));
  29.         /// <summary>
  30.         /// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
  31.         /// </summary>
  32.         /// <param name="provider">The service provider used to resolve dependencies</param>
  33.         /// <param name="instanceType">The type to activate</param>
  34.         /// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
  35.         /// <returns>An activated object of type instanceType</returns>
  36.         public static object CreateInstance(IServiceProvider provider, Type instanceType, params object[] parameters)
  37.         {
  38.             int bestLength = -1;
  39.             var seenPreferred = false;
  40.             ConstructorMatcher bestMatcher = default;
  41.             if (!instanceType.GetTypeInfo().IsAbstract)
  42.             {
  43.                 foreach (var constructor in instanceType
  44.                     .GetTypeInfo()
  45.                     .DeclaredConstructors)
  46.                 {
  47.                     if (!constructor.IsStatic && constructor.IsPublic)
  48.                     {
  49.                         var matcher = new ConstructorMatcher(constructor);
  50.                         var isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
  51.                         var length = matcher.Match(parameters);
  52.                         if (isPreferred)
  53.                         {
  54.                             if (seenPreferred)
  55.                             {
  56.                                 ThrowMultipleCtorsMarkedWithAttributeException();
  57.                             }
  58.                             if (length == -1)
  59.                             {
  60.                                 ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
  61.                             }
  62.                         }
  63.                         if (isPreferred || bestLength < length)
  64.                         {
  65.                             bestLength = length;
  66.                             bestMatcher = matcher;
  67.                         }
  68.                         seenPreferred |= isPreferred;
  69.                     }
  70.                 }
  71.             }
  72.             if (bestLength == -1)
  73.             {
  74.                 var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.";
  75.                 throw new InvalidOperationException(message);
  76.             }
  77.             return bestMatcher.CreateInstance(provider);
  78.         }
  79.         /// <summary>
  80.         /// Create a delegate that will instantiate a type with constructor arguments provided directly
  81.         /// and/or from an <see cref="IServiceProvider"/>.
  82.         /// </summary>
  83.         /// <param name="instanceType">The type to activate</param>
  84.         /// <param name="argumentTypes">
  85.         /// The types of objects, in order, that will be passed to the returned function as its second parameter
  86.         /// </param>
  87.         /// <returns>
  88.         /// A factory that will instantiate instanceType using an <see cref="IServiceProvider"/>
  89.         /// and an argument array containing objects matching the types defined in argumentTypes
  90.         /// </returns>
  91.         public static ObjectFactory CreateFactory(Type instanceType, Type[] argumentTypes)
  92.         {
  93.             FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructor, out int?[] parameterMap);
  94.             var provider = Expression.Parameter(typeof(IServiceProvider), "provider");
  95.             var argumentArray = Expression.Parameter(typeof(object[]), "argumentArray");
  96.             var factoryExpressionBody = BuildFactoryExpression(constructor, parameterMap, provider, argumentArray);
  97.             var factoryLamda = Expression.Lambda<Func<IServiceProvider, object[], object>>(
  98.                 factoryExpressionBody, provider, argumentArray);
  99.             var result = factoryLamda.Compile();
  100.             return result.Invoke;
  101.         }
  102.         /// <summary>
  103.         /// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
  104.         /// </summary>
  105.         /// <typeparam name="T">The type to activate</typeparam>
  106.         /// <param name="provider">The service provider used to resolve dependencies</param>
  107.         /// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
  108.         /// <returns>An activated object of type T</returns>
  109.         public static T CreateInstance<T>(IServiceProvider provider, params object[] parameters)
  110.         {
  111.             return (T)CreateInstance(provider, typeof(T), parameters);
  112.         }
  113.         /// <summary>
  114.         /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
  115.         /// </summary>
  116.         /// <typeparam name="T">The type of the service</typeparam>
  117.         /// <param name="provider">The service provider used to resolve dependencies</param>
  118.         /// <returns>The resolved service or created instance</returns>
  119.         public static T GetServiceOrCreateInstance<T>(IServiceProvider provider)
  120.         {
  121.             return (T)GetServiceOrCreateInstance(provider, typeof(T));
  122.         }
  123.         /// <summary>
  124.         /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
  125.         /// </summary>
  126.         /// <param name="provider">The service provider</param>
  127.         /// <param name="type">The type of the service</param>
  128.         /// <returns>The resolved service or created instance</returns>
  129.         public static object GetServiceOrCreateInstance(IServiceProvider provider, Type type)
  130.         {
  131.             return provider.GetService(type) ?? CreateInstance(provider, type);
  132.         }
  133.         private static MethodInfo GetMethodInfo<T>(Expression<T> expr)
  134.         {
  135.             var mc = (MethodCallExpression)expr.Body;
  136.             return mc.Method;
  137.         }
  138.         private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
  139.         {
  140.             var service = sp.GetService(type);
  141.             if (service == null && !isDefaultParameterRequired)
  142.             {
  143.                 var message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'.";
  144.                 throw new InvalidOperationException(message);
  145.             }
  146.             return service;
  147.         }
  148.         private static Expression BuildFactoryExpression(
  149.             ConstructorInfo constructor,
  150.             int?[] parameterMap,
  151.             Expression serviceProvider,
  152.             Expression factoryArgumentArray)
  153.         {
  154.             var constructorParameters = constructor.GetParameters();
  155.             var constructorArguments = new Expression[constructorParameters.Length];
  156.             for (var i = 0; i < constructorParameters.Length; i++)
  157.             {
  158.                 var constructorParameter = constructorParameters[i];
  159.                 var parameterType = constructorParameter.ParameterType;
  160.                 var hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(constructorParameter, out var defaultValue);
  161.                 if (parameterMap[i] != null)
  162.                 {
  163.                     constructorArguments[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i]));
  164.                 }
  165.                 else
  166.                 {
  167.                     var parameterTypeExpression = new Expression[] { serviceProvider,
  168.                         Expression.Constant(parameterType, typeof(Type)),
  169.                         Expression.Constant(constructor.DeclaringType, typeof(Type)),
  170.                         Expression.Constant(hasDefaultValue) };
  171.                     constructorArguments[i] = Expression.Call(GetServiceInfo, parameterTypeExpression);
  172.                 }
  173.                 // Support optional constructor arguments by passing in the default value
  174.                 // when the argument would otherwise be null.
  175.                 if (hasDefaultValue)
  176.                 {
  177.                     var defaultValueExpression = Expression.Constant(defaultValue);
  178.                     constructorArguments[i] = Expression.Coalesce(constructorArguments[i], defaultValueExpression);
  179.                 }
  180.                 constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType);
  181.             }
  182.             return Expression.New(constructor, constructorArguments);
  183.         }
  184.         private static void FindApplicableConstructor(
  185.             Type instanceType,
  186.             Type[] argumentTypes,
  187.             out ConstructorInfo matchingConstructor,
  188.             out int?[] parameterMap)
  189.         {
  190.             matchingConstructor = null;
  191.             parameterMap = null;
  192.             if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap) &&
  193.                 !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap))
  194.             {
  195.                 var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.";
  196.                 throw new InvalidOperationException(message);
  197.             }
  198.         }
  199.         // Tries to find constructor based on provided argument types
  200.         private static bool TryFindMatchingConstructor(
  201.             Type instanceType,
  202.             Type[] argumentTypes,
  203.             ref ConstructorInfo matchingConstructor,
  204.             ref int?[] parameterMap)
  205.         {
  206.             foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors)
  207.             {
  208.                 if (constructor.IsStatic || !constructor.IsPublic)
  209.                 {
  210.                     continue;
  211.                 }
  212.                 if (TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap))
  213.                 {
  214.                     if (matchingConstructor != null)
  215.                     {
  216.                         throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor.");
  217.                     }
  218.                     matchingConstructor = constructor;
  219.                     parameterMap = tempParameterMap;
  220.                 }
  221.             }
  222.             return matchingConstructor != null;
  223.         }
  224.         // Tries to find constructor marked with ActivatorUtilitiesConstructorAttribute
  225.         private static bool TryFindPreferredConstructor(
  226.             Type instanceType,
  227.             Type[] argumentTypes,
  228.             ref ConstructorInfo matchingConstructor,
  229.             ref int?[] parameterMap)
  230.         {
  231.             var seenPreferred = false;
  232.             foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors)
  233.             {
  234.                 if (constructor.IsStatic || !constructor.IsPublic)
  235.                 {
  236.                     continue;
  237.                 }
  238.                 if (constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false))
  239.                 {
  240.                     if (seenPreferred)
  241.                     {
  242.                         ThrowMultipleCtorsMarkedWithAttributeException();
  243.                     }
  244.                     if (!TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap))
  245.                     {
  246.                         ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
  247.                     }
  248.                     matchingConstructor = constructor;
  249.                     parameterMap = tempParameterMap;
  250.                     seenPreferred = true;
  251.                 }
  252.             }
  253.             return matchingConstructor != null;
  254.         }
  255.         // Creates an injective parameterMap from givenParameterTypes to assignable constructorParameters.
  256.         // Returns true if each given parameter type is assignable to a unique; otherwise, false.
  257.         private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap)
  258.         {
  259.             parameterMap = new int?[constructorParameters.Length];
  260.             for (var i = 0; i < argumentTypes.Length; i++)
  261.             {
  262.                 var foundMatch = false;
  263.                 var givenParameter = argumentTypes[i].GetTypeInfo();
  264.                 for (var j = 0; j < constructorParameters.Length; j++)
  265.                 {
  266.                     if (parameterMap[j] != null)
  267.                     {
  268.                         // This ctor parameter has already been matched
  269.                         continue;
  270.                     }
  271.                     if (constructorParameters[j].ParameterType.GetTypeInfo().IsAssignableFrom(givenParameter))
  272.                     {
  273.                         foundMatch = true;
  274.                         parameterMap[j] = i;
  275.                         break;
  276.                     }
  277.                 }
  278.                 if (!foundMatch)
  279.                 {
  280.                     return false;
  281.                 }
  282.             }
  283.             return true;
  284.         }
  285.         private struct ConstructorMatcher
  286.         {
  287.             private readonly ConstructorInfo _constructor;
  288.             private readonly ParameterInfo[] _parameters;
  289.             private readonly object[] _parameterValues;
  290.             public ConstructorMatcher(ConstructorInfo constructor)
  291.             {
  292.                 _constructor = constructor;
  293.                 _parameters = _constructor.GetParameters();
  294.                 _parameterValues = new object[_parameters.Length];
  295.             }
  296.             public int Match(object[] givenParameters)
  297.             {
  298.                 var applyIndexStart = 0;
  299.                 var applyExactLength = 0;
  300.                 for (var givenIndex = 0; givenIndex != givenParameters.Length; givenIndex++)
  301.                 {
  302.                     var givenType = givenParameters[givenIndex]?.GetType().GetTypeInfo();
  303.                     var givenMatched = false;
  304.                     for (var applyIndex = applyIndexStart; givenMatched == false && applyIndex != _parameters.Length; ++applyIndex)
  305.                     {
  306.                         if (_parameterValues[applyIndex] == null &&
  307.                             _parameters[applyIndex].ParameterType.GetTypeInfo().IsAssignableFrom(givenType))
  308.                         {
  309.                             givenMatched = true;
  310.                             _parameterValues[applyIndex] = givenParameters[givenIndex];
  311.                             if (applyIndexStart == applyIndex)
  312.                             {
  313.                                 applyIndexStart++;
  314.                                 if (applyIndex == givenIndex)
  315.                                 {
  316.                                     applyExactLength = applyIndex;
  317.                                 }
  318.                             }
  319.                         }
  320.                     }
  321.                     if (givenMatched == false)
  322.                     {
  323.                         return -1;
  324.                     }
  325.                 }
  326.                 return applyExactLength;
  327.             }
  328.             public object CreateInstance(IServiceProvider provider)
  329.             {
  330.                 for (var index = 0; index != _parameters.Length; index++)
  331.                 {
  332.                     if (_parameterValues[index] == null)
  333.                     {
  334.                         var value = provider.GetService(_parameters[index].ParameterType);
  335.                         if (value == null)
  336.                         {
  337.                             if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out var defaultValue))
  338.                             {
  339.                                 throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[index].ParameterType}' while attempting to activate '{_constructor.DeclaringType}'.");
  340.                             }
  341.                             else
  342.                             {
  343.                                 _parameterValues[index] = defaultValue;
  344.                             }
  345.                         }
  346.                         else
  347.                         {
  348.                             _parameterValues[index] = value;
  349.                         }
  350.                     }
  351.                 }
  352. #if NETCOREAPP
  353.                 return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
  354. #else
  355.                 try
  356.                 {
  357.                     return _constructor.Invoke(_parameterValues);
  358.                 }
  359.                 catch (TargetInvocationException ex) when (ex.InnerException != null)
  360.                 {
  361.                     ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
  362.                     // The above line will always throw, but the compiler requires we throw explicitly.
  363.                     throw;
  364.                 }
  365. #endif
  366.             }
  367.         }
  368.         private static void ThrowMultipleCtorsMarkedWithAttributeException()
  369.         {
  370.             throw new InvalidOperationException($"Multiple constructors were marked with {nameof(ActivatorUtilitiesConstructorAttribute)}.");
  371.         }
  372.         private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments()
  373.         {
  374.             throw new InvalidOperationException($"Constructor marked with {nameof(ActivatorUtilitiesConstructorAttribute)} does not accept all given argument types.");
  375.         }
  376.     }
  377. }
复制代码
Microsoft.Extensions.Internal.ActivatorUtilities类源码仔细阅读上面的源码后我们可以发现,它最终也是调用 app.Use(...) 这个方法的,此外我们可以得出一些结论,如下:
关于自定义中间件的方法:
1、中间件的方法名必须叫 Invoke 或者 InvokeAsync ,且为 public ,非 static 。
2、Invoke 或者 InvokeAsync 方法第一个参数必须是 HttpContext 类型。
3、Invoke 或者 InvokeAsync 方法的返回值类型必须是 Task 。
4、Invoke 或者 InvokeAsync 方法可以有多个参数,除 HttpContext 外其它参数会尝试从依赖注入容器中获取。
5、Invoke 或者 InvokeAsync 方法不能有重载。
 
关于自定义中间件的构造函数:
1、构造函数必须包含 RequestDelegate 参数,该参数传入的是下一个中间件。
2、构造函数参数中的 RequestDelegate 参数不是必须放在第一个,可以是任意位置。
3、构造函数可以有多个参数,参数会优先从给定的参数列表中查找,其次会从依赖注入容器中获取,获取失败会尝试获取默认值,都失败则会抛出异常。
4、构造函数可以有多个,届时会根据构造函数参数列表和给定的参数列表选择匹配度最高的一个。
 
个人建议:
1、除极特殊情况外只保留一个构造函数,以省去多余的构造函数匹配检查。
2、在构造函数中注入所需依赖而不是在 Invoke 或者 InvokeAsync 方法中注入。
3、关于构造函数参数的顺序,把 RequestDelegate 放在第一个;之后是 UseMiddleware 方法中给出的参数,而且构造函数中参数顺序和给定参数列表中的顺序最好也相同;然后是需要注入的参数;最后是有默认值的参数。以上除了默认值参数必须放在最后外其余的顺序都不是必须的,但按照上面的顺序会比较清晰,而且能使实例创建的开销最小。
4、Invoke 或者 InvokeAsync 方法只保留一个 HttpContext 参数,这样可以省去对 Invoke 或者 InvokeAsync 方法的二次包装。
 
本文部分内容参考博文:https://my.oschina.net/u/3772973/blog/4626207
更多关于ASP.NET Core 中间件的相关知识可参考微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0
至此本文就全部介绍完了,如果觉得对您有所启发请记得点个赞哦!!!
 
Demo源码:
  1. 链接:https://pan.baidu.com/s/11NLDtt_cKPFxDbA3fW8Btg
  2. 提取码:0hyo
复制代码
此文由博主精心撰写转载请保留此原文链接:https://www.cnblogs.com/xyh9039/p/16414344.html
版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!! 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

干翻全岛蛙蛙

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表