Simple pipeline simulation

Simple pipeline simulation

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using static ConsolePipeline.Program;
using System.Linq;

namespace ConsolePipeline
{
    public class Program
    {
        public delegate Task RequestDelegate(Httpcontext httpcontext);
        static void Main(string[] args)
        {
            ApplicationBuilder app = new ApplicationBuilder();
            app.Use(the async (context, Next) => 
            { 
                Console.WriteLine ( " first started ... " );
                 the await Next (); 
                Console.WriteLine ( " first end ... " ); 
            }); 
            app.Use ( the async (context, Next) => 
            { 
                Console.WriteLine ( " start the second ... " );
                 the await Next (); 
                Console.WriteLine ( " second end ... " ); 
            }); 
            var firstmiddleware = app.Build();
            firstmiddleware(new Httpcontext());
            Console.WriteLine("Hello World!");
        }
    }

    public class Httpcontext { }

    public class ApplicationBuilder
    {
        //中间的委托,不是中间件
        public static readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();

        //原生Use
        public ApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _components.Add(middleware);
            return this;
        }

        // 扩展Use
        public ApplicationBuilder Use(Func<Httpcontext, Func<Task>, Task> middleware)
        {
            return Use(next =>
            {
                return context =>
                {
                    Task SimpleNext() => next(context);
                    return middleware(context, SimpleNext);
                };
            });
        }

        public RequestDelegate Build()
        {
            RequestDelegate app = next =>
            {
                Console.WriteLine("中间中间件。。。");
                return Task.CompletedTask;
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }
            return app;
        }
    }
}

running result:

 

Guess you like

Origin www.cnblogs.com/1175429393wljblog/p/12302074.html