1. はじめに
- C#でJavaのSprping AOPと同じに様なことをしたい
- メソッドの実行前、後に共通ログを出力したい
2. 開発環境
- C#
- .NET 6
- Visual Studio 2022
- MethodBoundaryAspect.Fody (NuGet)
- Windows 11
3. 事前準備
4. ソースコード
4.1. Aspectコード
LogAttribute.cs
using static System.Console;
using MethodBoundaryAspect.Fody.Attributes;
using System.Diagnostics;
public sealed class LogAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Debug.Print("On entry");
}
public override void OnExit(MethodExecutionArgs args)
{
Debug.Print("On exit");
}
public override void OnException(MethodExecutionArgs args)
{
Debug.Print("On exception");
}
}
4.2. サンプルコード
[Log]
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
[Log]
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("NG");
throw new Exception();
}
4.3. 実行結果
- OKの場合
On entry
On exit
- NGの場合
On entry
On exception
5. 参考文献