.NET Core: attributes that execute before and after method

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

    This can be accomplished using DynamicProxy.

    There is an implementation of a memory caching technique with logic that executes before the method being called. That can be extended to check for the existence of an attribute like this

    var attribute = Attribute.GetCustomAttribute(invocation.MethodInvocationTarget, typeof(CachedAttribute)) as CachedAttribute;
    if (attribute != null)
    {
      ...
    }
    

    The code above can be inside the Intercept method in the Interceptor implementation. CachedAttribute would be your attribute.

提交回复
热议问题