hangfire filter实现

internal class Program
{
    static async Task Main(string[] args)
    {
        var filters = new List<IFilter>
        {
            new FilterA(),
            new FilterB(),
        };

        Func<BackgroundJob> continuation = () =>
        {
            return new BackgroundJob();
        };

        filters.Reverse();
        var thunk = filters.Aggregate(continuation, 
            (next, filter) => () => InvokeClientFilter(filter, next));

        thunk();
    }

    private static BackgroundJob InvokeClientFilter(IFilter filter, Func<BackgroundJob> next)
    {
        filter.OnCreating();
        var backgroungJob = next();
        filter.OnCreated();
        return backgroungJob;
    }
}

public class FilterA : IFilter
{
    public void OnCreated()
    {
        Console.WriteLine("FilterA: OnCreated");
    }

    public void OnCreating()
    {
        Console.WriteLine("FilterA: OnCreating");
    }
}

public interface IFilter
{
    void OnCreating();
    void OnCreated();
}

public class FilterB : IFilter
{
    public void OnCreated()
    {
        Console.WriteLine("FilterB: OnCreated");
    }

    public void OnCreating()
    {
        Console.WriteLine("FilterB: OnCreating");
    }
}

public class BackgroundJob
{

}
posted @ 2024-10-26 14:58  pojianbing  阅读(2)  评论(0编辑  收藏  举报