繁体   English   中英

如何在接口实现代码C#之前执行一个默认方法?

[英]How to execute a default method before the interface implementation code C#?

我有一个只实现一种方法的接口:

public interface IHandler<T> where T : Comand
{
    Task<IResultComand> HandlerAsync(T comand);
}

我在我的课程中使用它如下:

public class ProductHandler : IHandler<NewProductComand>,
                              IHandler<EditProductComand>,
                              IHandler<DeleteProductComand>

public async Task<IResultComand> HandlerAsync(NewProductComand comand) 
{
        ResultComand result = new();

        comand.Validate();
        if (!comand.Valid)
        {
            return result;
        }

        //Create new product

        return result;
}

public async Task<IResultComand> HandlerAsync(EditProductComand comand) 
{
        ResultComand result = new();

        comand.Validate();
        if (!comand.Valid)
        {
            return result;
        }

        //Edit product

        return result;
}

public async Task<IResultComand> HandlerAsync(DeleteProductComand comand) 
{
        ResultComand result = new();

        comand.Validate();
        if (!comand.Valid)
        {
            return result;
        }

        //Delete product

        return result;
}

我的Comand有以下代码:

 public abstract class Comand
 {
    public bool Valid { get; set; }

    public abstract void Validate();
 }

如何让下面的代码在执行HandlerAsync中的实现代码之前隐式运行? (有些东西像ActionFilter Web API .NET)

    ResultComand result = new();

    comand.Validate();
    if (!comand.Valid)
    {
        return result;
    }

您正在寻找装饰者模式。

基本上,您保留“基础”CommandHandler 原样并让它完成其工作,但您添加了一个额外的 class 来实现相同的接口:

ExtraStuffCommandHandlerDecorator<TComand> : IHandler<TComand>
    where TComand : Comand
{
    readonly IHandler<TComand> _decorated;

    public ExtraStuffCommandHandlerDecorator(IHandler<TComand> decorated)
    {
        _decorated = decorated;
    }

    public async Task<IResultComand> HandlerAsync(TComand comand)
    {
        // Do stuff before base command execution

        IResultComand result = await _decorated.HandlerAsync(comand);

        // Do stuff after base command execution

        return result;
    }
}

现在,当前正在直接实例化和调用基本处理程序的调解器应该查找装饰器并调用它,将基本处理程序作为构造函数参数传入。

Autofac 的 RegisterGenericDecorator 方法很好地支持使用装饰器。 使用 Asp Core DI 的实现稍微复杂一些,但这里有一个指南。

https://andrewlock.net/adding-decorated-classes-to-the-asp.net-core-di-container-using-scrutor/#manually-creating-decorators-with-the-asp.net-core-di 的-容器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM