如何执行默认方法之前的接口实现代码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;
}

你要找的是Decorator Pattern

基本上,你让你的'base' CommandHandler保持原样,让它做它的工作,但你添加一个额外的类来实现相同的接口:

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;
}
}

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

autofacc的RegisterGenericDecorator方法很好地支持使用decorator。使用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-container