.NET Core: attributes that execute before and after method

前端 未结 4 1972
余生分开走
余生分开走 2021-01-12 17:10

In Java, it is possible to use AspectJ for adding behavior before and after executing a method, using method annotations. Since C# Attributes seem to be very similar, I was

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 17:32

    You need some framework that is able to handle your attribute appropriately. Only because the attribute exists doesn´t mean it will have any affect.

    I wrote some easy engine that does that. It will determine if the attribute is present on the passed action and if so get the reflected methods in order to execute them.

    class Engine
    {
        public void Execute(Action action)
        {
            var attr = action.Method.GetCustomAttributes(typeof(MyAttribute), true).First() as MyAttribute;
            var method1 = action.Target.GetType().GetMethod(attr.PreAction);
            var method2 = action.Target.GetType().GetMethod(attr.PostAction);
    
            // now first invoke the pre-action method
            method1.Invoke(null, null);
            // the actual action
            action();
            // the post-action
            method2.Invoke(null, null);
        }
    }
    public class MyAttribute : Attribute
    {
        public string PreAction;
        public string PostAction;
    }
    

    Of course you need some null-ckecks, e.g. in the case the methods don´t exist or aren´t static.

    Now you have to decorate your action with the attribute:

    class MyClass
    {
        [MyAttribute(PreAction = "Handler1", PostAction = "Handler2")]
        public void DoSomething()
        {
            
        }
    
        public static void Handler1()
        {
            Console.WriteLine("Pre");
        }
        public static void Handler2()
        {
            Console.WriteLine("Post");
        }
    }
    

    Finally you can execute that method within our engine:

    var engine = new Engine();
    var m = new MyClass();
    engine.Execute(m.DoSomething);
    

提交回复
热议问题