首页 > 解决方案 > PostSharp - 记录器作为方面参数

问题描述

想要将PostSharp诊断与封装在库程序集中的异常处理方面结合使用。

同时尝试在该诊断库的消费者程序集中设置和初始化Serilog 记录器。

[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.After,
  typeof(AddContextOnExceptionAttribute))]
[PSerializable]
public sealed class ReportAndSwallowExceptionAttribute : OnExceptionAspect
{
    public ILogger TheLogger { get; set; }

    public ReportAndSwallowExceptionAttribute(ILogger logger)
    {
        TheLogger = logger;
    }

    public override void OnException(MethodExecutionArgs args)
    {
        TheLogger.Error("Error happened ...");
    }
 }

在主课中:

    class Program
    {
        // below line is the critical part which seems ILogger is not allowed
        [ReportAndSwallowException(Log.Logger)]
        public static void TryExceptionMethod()
        {
            throw new NotImplementedException();
        }
        
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                    .WriteTo.File(@"HERE\Logs\log-x.log", 
                     rollingInterval: RollingInterval.Day)
                     .CreateLogger();

            Console.WriteLine("Hello World!");
            TryExceptionMethod();

        }    

    }

似乎传递ILogger给该属性是非法的,我该如何实现这种情况?

当前错误:

Error   CS0181: Attribute constructor parameter 'logger' has type 'ILogger', which is not a valid attribute parameter type  

认为这个错误需要一个常量来解决,但主要问题是如何实现这个场景:在消费者项目中有记录器,在库中有方面。

标签: c#attributespostsharp

解决方案


这里最简单的选择是您的方面直接引用 Log.Logger。

这里记录了其他几个更复杂的选项:https ://doc.postsharp.net/sumption-dependencies


推荐阅读