.NET Core: attributes that execute before and after method

前端 未结 4 1975
余生分开走
余生分开走 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:34

    The question is similar to Run a method before all methods of a class, hence the same answer applies to both. Use https://github.com/Fody/Fody . The licencing model is based on voluntary contributions making it the better option to PostSharp which is a bit expensive for my taste.

    [module: Interceptor]
    namespace GenericLogging
    {
    
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
        public class InterceptorAttribute : Attribute, IMethodDecorator
        {
            // instance, method and args can be captured here and stored in attribute instance fields
            // for future usage in OnEntry/OnExit/OnException
            public void Init(object instance, MethodBase method, object[] args)
            {
                Console.WriteLine(string.Format("Init: {0} [{1}]", method.DeclaringType.FullName + "." + method.Name, args.Length));
            }
    
            public void OnEntry()
            {
                Console.WriteLine("OnEntry");
            }
    
            public void OnExit()
            {
                Console.WriteLine("OnExit");
            }
    
            public void OnException(Exception exception)
            {
                Console.WriteLine(string.Format("OnException: {0}: {1}", exception.GetType(), exception.Message));
            }
        }
    
        public class Sample
        {
            [Interceptor]
            public void Method(int test)
            {
                Console.WriteLine("Your Code");
            }
        }
    }
    
    [TestMethod]
    public void TestMethod2()
    {
        Sample t = new Sample();
        t.Method(1);
    }
    

提交回复
热议问题