在.NET Core 2.1中使用AOP进行记录 [英] Logging using AOP in .NET Core 2.1

查看:726
本文介绍了在.NET Core 2.1中使用AOP进行记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为.NET Core 2.1解决方案中的日志记录实现AOP.我以前从未使用过它,而我一直在网上寻找,似乎看不到任何有人在Core 2中使用它的示例.有人知道我会怎么做吗?

I want to implement AOP for the logging in my .NET Core 2.1 solution. I've never used it before and I've been looking online and cant seem to see any examples of people using it with Core 2. Does anyone know how i would go about this?

例如,哪些软件包可用于AOP,并有示例代码可以帮助我入门?我使用的是带有.net核心的内置DI,因此我不必担心该部分.

For example what packages to use for AOP and have any example code to get me started? Im using the built in DI with .net core so i dont need to worry about that part.

推荐答案

Microsoft DI不提供诸如拦截器或装饰器之类的高级方案(使用Microsoft DI的装饰器有一种解决方法:

Microsoft DI does not offer advances scenarios such as interceptor or decorators(there is a workaround for decorators using Microsoft DI: https://medium.com/@willie.tetlow/net-core-dependency-injection-decorator-workaround-664cd3ec1246).

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

You can implement AOP by using Autofac (https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html) or Simple injector with dynamic proxy. Both have a really good documentation. Simple injector doesn't have an out of the box solution for interception because of their design rules but you can add an extension for it (http://simpleinjector.readthedocs.io/en/latest/aop.html).

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

Here is a basic AOP scenario from the official SI documentation:(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));
    }
}

这篇关于在.NET Core 2.1中使用AOP进行记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆