簡體   English   中英

在.NET Core 2.1中使用AOP進行日志記錄

[英]Logging using AOP in .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 )或帶有動態代理的簡單注入器來實現AOP。 兩者都有很好的文檔。 簡單的注入器由於其設計規則而沒有開箱即用的攔截解決方案,但您可以為其添加擴展( 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));
    }
}

免責聲明:我是此解決方案的制作人

微軟並沒有提供AOP解掉凈芯盒。 但是,我已經制作了第三方項目可能有所幫助。 它直接與Net Core配合使用,並通過應用程序中的ServiceCollection注冊插入。

Microsoft提供的是一個名為System.Runtime.DispatchProxy的庫,可用於為類創建代理對象。 但是,這個代理本身並不特別有用或功能豐富,並且需要大量額外代碼才能獲得與Castle Proxy(眾所周知的動態代理庫)相關的內容。

考慮到這一點,我創建了一個庫,它將DispatchProxy包裝成代碼,可以在應用程序啟動期間的ServiceCollection配置中輕松注入。 訣竅是有一種方法來創建屬性和一個可以應用於您的方法的配對攔截器。 然后在Proxy包裝期間讀取該屬性,並調用相關的Interceptor。

這是攔截器屬性的示例

public class ConsoleLogAttribute : MethodInterceptorAttribute
{
}

這是一個示例Interceptor類

public class ConsoleLogInterceptor : MethodInterceptor
{
    public override void BeforeInvoke(IInterceptionContext interceptionContext)
    {
        Console.WriteLine($"Method executing: {interceptionContext.CurrentMethod.Name}");
    }

    public override void AfterInvoke(IInterceptionContext interceptionContext, object methodResult)
    {
        Console.WriteLine($"Method executed: {interceptionContext.CurrentMethod.Name}");
    }
}

這是它如何應用於您的方法

[ConsoleLog]
public void TestMethod()
{
}

最后,這就是它將如何添加到您的ServiceCollection配置中(假設您想要代理的類被稱為[TestClass]:

public void ConfigureServices(IServiceCollection services)
{
    // Configure Simple Proxy
    services.EnableSimpleProxy(p => p.AddInterceptor<ConsoleLogAttribute, ConsoleLogInterceptor>());

    // Configure your services using the Extension Methods
    services.AddTransientWithProxy<ITestClass, TestClass>();
}

看看這個GitHub項目: https//github.com/f135ta/SimpleProxy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM