4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でAOPを実装したい

Posted at

1. はじめに

  • C#でJavaのSprping AOPと同じに様なことをしたい
  • メソッドの実行前、後に共通ログを出力したい

2. 開発環境

  • C#
  • .NET 6
  • Visual Studio 2022
  • MethodBoundaryAspect.Fody (NuGet)
  • Windows 11

3. 事前準備

  • NuGetからMethodBoundaryAspect.Fodyをインストールする
    image.png

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. 参考文献

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?