我有一個只實作一種方法的介面:
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;
}
uj5u.com熱心網友回復:
您正在尋找裝飾器模式。
基本上,您將“基本”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;
}
}
現在,您當前正在實體化并直接呼叫基本處理程式的調解器應該改為查找裝飾器并呼叫它,將基本處理程式作為建構式引數傳入。
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 -容器
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465791.html
