我正在设计一个遵循责任链模式的处理程序管道。
管道处理程序具有以下接口:
public interface IPipelineHandler<TContext>
{
Func<TContext, Task> Next { get; set; }
Task HandleAsync(TContext context);
}
每个处理程序都对管道中下一个处理程序有一个引用。以下类用于构建管道:
public class PipelineBuilder<TContext>
{
private readonly List<IPipelineHandler<TContext>> handlers
= new List<IPipelineHandler<TContext>>();
public PipelineBuilder<TContext> Register(IPipelineHandler<TContext> handler)
{
handlers.Add(handler);
return this;
}
public Func<TContext, Task> Build()
{
IPipelineHandler<TContext> root = null;
IPipelineHandler<TContext> prev = null;
foreach (var handler in handlers)
{
if (root == null)
{
root = handler;
}
else
{
prev.Next = ctx => handler.HandleAsync(ctx);
}
prev = handler;
}
return root.HandleAsync;
}
}
当前实现的缺陷在于,管道中的每个处理程序都是预先构建的。我想按需构建每个处理程序,因此不是将处理程序实例传递给构建函数,而是传递一个
Func<IPipelineHandler<TContext>>
。为了使每个管道处理程序只在调用时创建,我需要对
Build()
进行哪些修改呢?如果还不清楚,请注意:每个处理程序应该只在由管道中的前一个处理程序调用时创建,而不是在 Build() 方法期间创建。
IPipelineHandler
实例,你可以使用具体的Type
进行注册,然后使用该Type
按需解析实例。 - LuisoHttpClient
和ASP.NET Web API服务器的DelegatingHandler
组合:https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Net.Http.Formatting/HttpClientFactory.cs#L57-L89 - tugberk