c# - 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
认为这个错误需要一个常量来解决,但主要问题是如何实现这个场景:在消费者项目中有记录器,在库中有方面。
解决方案
这里最简单的选择是您的方面直接引用 Log.Logger。
这里记录了其他几个更复杂的选项:https ://doc.postsharp.net/sumption-dependencies
推荐阅读
- azure - 使用 Azure Cli 删除 Azure 文件共享中的旧文件
- python - 熊猫每周时间表,包括假期
- node.js - 我需要在 NPM package.json 和主 index.html 中添加 Babel 和 React 还是只在一个地方就足够了?
- php - 使用 Str::random (或原生 php 方法)的两个标记重合的情况
- reactjs - 如何在 React Native 中实现类似 Android 片段的功能
- c# - 打开包含同名文件的 Zip 文件
- ionic-framework - 使用 Ionic 的移动辅助功能不起作用
- python - 为什么我不能在 VSCode 中查看 Python 某些模块的定义?
- azure-data-factory - 如何获取映射数据流内部的映射数据流名称?
- python - 如何在 Python 中将 Azure Blob 存储中的 CSV 作为流处理