gpt4 book ai didi

c# - C# 中的完整惰性管道

转载 作者:行者123 更新时间:2023-11-30 12:41:16 25 4
gpt4 key购买 nike

我正在设计一个遵循责任链模式的处理程序管道。

管道处理程序具有以下接口(interface):

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()做哪些修改?为了与Func<IPipelineHandler<TContext>>一起工作这样每个管道处理程序只在调用时创建?

以防万一不清楚 - 每个处理程序应该仅在它被管道中的前一个处理程序调用时创建,而不是在 Build() 方法期间创建。

最佳答案

最终解决方案非常简单。我创建了一个 LazyPipelineHandler 包装器,这样我仍然可以构建管道但不会实例化包装的处理程序,直到它实际需要执行为止:

public class LazyPipelineHandler<TContext> : PipelineHandler<TContext>
{
private readonly Lazy<IPipelineHandler<TContext>> innerHandler;

public LazyPipelineHandler(Func<IPipelineHandler<TContext>> handlerFactory)
{
this.innerHandler = new Lazy<IPipelineHandler<TContext>>(handlerFactory);
}

public override Task HandleAsync(TContext context, Func<TContext, Task> next)
{
innerHandler.Value.Next = next;
return innerHandler.Value.HandleAsync(context);
}
}

关于c# - C# 中的完整惰性管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38015323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com