c# - 在 .NET Core 2.1 中使用 AOP 进行日志记录

标签 c# logging asp.net-core aop asp.net-core-2.1

我想在我的 .NET Core 2.1 解决方案中为日志记录实现 AOP。我以前从未使用过它,我一直在网上查找,但似乎看不到有人将它与 Core 2 一起使用的任何示例。有谁知道我将如何处理这个问题?

例如,AOP 使用哪些包?有任何示例代码可以帮助我入门吗?我将内置的 DI 与 .net 核心一起使用,所以我不需要担心那部分。

最佳答案

Microsoft DI 不提供高级方案,例如拦截器或装饰器(使用 Microsoft DI 的装饰器有一个解决方法:https://medium.com/@willie.tetlow/net-core-dependency-injection-decorator-workaround-664cd3ec1246)。

您可以使用 Autofac ( https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html ) 或带有动态代理的简单注入(inject)器来实现 AOP。两者都有非常好的文档。由于其设计规则,简单注入(inject)器没有开箱即用的拦截解决方案,但您可以为其添加扩展(http://simpleinjector.readthedocs.io/en/latest/aop.html)。

这是来自官方 SI 文档的基本 AOP 场景:( http://simpleinjector.readthedocs.io/en/latest/InterceptionExtensions.html ):

//Add registration to the composition root
container.InterceptWith<MonitoringInterceptor>(serviceType => serviceType.Name.EndsWith("Repository"));`

// Here is an example of an interceptor implementation.
// NOTE: Interceptors must implement the IInterceptor interface:
private class MonitoringInterceptor : IInterceptor {
    private readonly ILogger logger;

  public MonitoringInterceptor(ILogger logger) {
        this.logger = logger;
    }

    public void Intercept(IInvocation invocation) {
        var watch = Stopwatch.StartNew();

        // Calls the decorated instance.
        invocation.Proceed();

        var decoratedType = invocation.InvocationTarget.GetType();

        this.logger.Log(string.Format("{0} executed in {1} ms.",
            decoratedType.Name, watch.ElapsedMilliseconds));
    }
}

关于c# - 在 .NET Core 2.1 中使用 AOP 进行日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51783365/

相关文章:

c# - 这个界面的最佳名称是什么?

c# - 为十进制值分配字符串值

c# - 如果我向 AddControllersWithViews() 添加扩展,它是否也适用于 AddRazorPages()

Django 日志位置

c# - 为什么在 ASP .NET Authorize 标记中总是返回 401(未经授权)?

razor - 复杂的自定义标签助手

c# - 您如何在 C# 中模拟文件系统以进行单元测试?

c# - 如何从 Socket 获取 IP 地址

azure - Azure 应用程序中缺少“应用程序服务日志”选项

jsp - Tomcat 8 启用调试日志记录以列出不需要的 jar