gpt4 book ai didi

c# - 如何管理装饰 ApiControllers 中的重复?

转载 作者:行者123 更新时间:2023-11-30 21:37:04 24 4
gpt4 key购买 nike

我目前正在从事一个项目,其中每个 API Controller 都需要记录事件。一个粗略的例子可能是:

[Route(...)]
public IHttpActionResult Foo(...)
{
using(var logger = ...)
{
// use the logger
return _service.Bar(...);
}
}

在我看来,这至少存在三个问题。

  1. 将日志记录横切关注点与违反单一职责原则的请求处理相结合。
  2. 使用 newlogger 实现耦合到 Controller ,这违反了依赖倒置原则。
  3. 在违反 DRY 的每个 Controller 的每个端点中重复使用

我认为我可以通过装饰 Controller 来修复 (1),(2) 使用基本 DI,以及 (3),我相信,结果会自行解决。但是,我通过装饰具有带有 Route 属性的端点的 Controller 来招致另一个重复问题。装饰 Controller 不应该让我依赖于特定的实现来处理路由,所以我在每个装饰中都需要它们(可能更多)或找到一种方法来继承或重用它们。

// I can fluently handle logging with a LoggingController
// but I still need the route attribute
[Route(...)]
public IHttpActionResult Foo(...)
{
return LogActivity(...).Foo(...);
}

private IController LogActivity(...)
{
// do logging
return _controller;
}

到目前为止,我认为我有两个可行的解决方案:

  1. 将抽象级别提升到可以继承属性的抽象类。
  2. 提供一个代理装饰,它简单地委托(delegate)给可能是最外层实际装饰的任何东西。

(1) 将我与一些基本实现结合起来,(2) 将我与每种 Controller 类型的代理/包装器结合起来。 (2) 似乎是更好的方法,但它的问题足以让人怀疑是否有一些 DI 或 AOP 模式可以处理这个问题。

// (2) with a decorator with no additional
// behavior or functionality delegates to
// the given implementation.
[Route(...)]
public IHttpActionResult Foo(...)
{
return _controller.Foo(...);
}

最佳答案

您可以使用 ASP.NET 的 HTTP 消息处理程序(ASP.NET Core 的中间件),您可以将其插入请求管道,对其余代码透明。通过这种方式,您可以实现横切关注点处理的正交性,并避免重复自己。

使用 ASP.NET 4.5+ 的 HTTP 消息处理程序示例:

public class RequestLoggingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// --> log begin of request
// for example, you can include time measurement
Stopwatch requestTime = Stopwatch.StartNew();

try
{
var response = await base.SendAsync(request, cancellationToken);
// --> log successful completion
return response;
}
catch (Exception e)
{
// --> log failure
throw;
}
}
}

这是你插入它的方式:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MessageHandlers.Add(new RequestLoggingHandler());

//... the rest of the setup...
}
}

在 ASP.NET Core 中,还有一个名为 Middleware 的新方法。此处有更多详细信息:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x#writing-middleware

关于c# - 如何管理装饰 ApiControllers 中的重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47627368/

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