1. 创建 Context.cs

using System;
using System.Threading.Tasks;

namespace MyPipeline
{
   public class Context{
       
   }
}

2. 创建 RequestDelegate.cs

using System;
using System.Threading.Tasks;

namespace MyPipeline
{
   public delegate Task RequestDelegate(Context context);
}

3. 具体实现

using System; 
using System.Collections.Generic; 
using System.Threading.Tasks; 

namespace MyPipeline {
    class Program {

        public static List < Func < RequestDelegate, RequestDelegate >> _list = new List < Func < RequestDelegate, RequestDelegate >> (); 
        static void Main(string[] args) {
            
           Use(next =>  {
                return context =>  {
                    System.Console.WriteLine("1"); 
                return  next.Invoke(context); 
                }; 
            }); 

            Use(next =>  {
                return context =>  {
                    System.Console.WriteLine("2"); 
                return  next.Invoke(context); 
                }; 
            }); 


            RequestDelegate end = (context) =>  {
                        System.Console.WriteLine("end ... "); 
                            return Task.CompletedTask; 

            }; 

            _list.Reverse(); 
            foreach (var middleware in _list) {
                end = middleware.Invoke(end); 

            }

            end.Invoke(new Context()); 

            Console.ReadLine(); 

        }


        public static void Use(Func < RequestDelegate, RequestDelegate > middleware) {
            _list.Add(middleware); 
        }
    }
}

4. 运行结果

1
2
end ...

 

相关文章:

  • 2021-11-12
  • 2021-06-15
  • 2021-05-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2021-08-15
  • 2021-12-27
  • 2022-03-08
  • 2022-01-22
  • 2021-06-26
  • 2022-12-23
相关资源
相似解决方案