title: .NET Core: attributes that execute before and after method
body: <p>In Java, it is possible to use AspectJ for adding behavior before and after executing a method, using <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html" rel="noreferrer">method annotations</a>. Since C# Attributes seem to be very similar, I was wondering whether it would be possible to achieve similar behavior. I was looking in several tutorials and other sources (<a href="https://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx" rel="noreferrer">1</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/" rel="noreferrer">2</a>, <a href="https://www.codeproject.com/Articles/827091/Csharp-Attributes-in-minutes" rel="noreferrer">3</a>), but none of them helped me.</p>
  
  <p>I thought that maybe I could be able to mimic the behavior by inserting the code into Attribute constructor and making it disposable, like this:</p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Method)]
  public class MyWritingAttribute : Attribute, IDisposable
  {
      public MyWritingAttribute()
      {
          Console.WriteLine("Attribute created");
      }
  
      public void Dispose()
      {
          Console.WriteLine("Attribute disposed");
      }
  }
  </code></pre>
  
  <p>However, when using the attribute like this, only <em>Hello world!</em> got displayed in the console:</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          SayHelloWorld();
          Console.ReadLine();
      }
  
      [MyWriting]
      private static void SayHelloWorld()
      {
          Console.WriteLine("Hello World!");
      }
  }
  </code></pre>
  
  <p>I was thinking that maybe Console is not reachable in the attribute, but even when replacing it with <code>throw new Exception()</code> expressions, no exception was thrown. How is it possible that <code>StringLengthAttribute</code> from EF works, but my attribute is not even instantiated? And how do I make the attribute run before and after the decorated method?</p>