2010-03-29 270 views
4

我試圖城堡攔截器中訪問應用的方法的自定義屬性,如:訪問自定義屬性

[MyCustomAttribute(SomeParam = "attributeValue")] 
public virtual MyEntity Entity { get; set; } 

使用下面的代碼:

internal class MyInterceptor : IInterceptor 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     if (invocation.Method.GetCustomAttributes(typeof(MyCustomAttribute), true) != null) 
     { 
      //Do something 
     } 
    } 
} 

攔截器在調用方法時觸發OK,但此代碼不返回自定義屬性。我怎樣才能做到這一點?

+0

您使用的是什麼版本DynamicProxy的? – 2010-03-29 14:12:41

+0

我正在使用版本2.1 – 2010-03-29 16:34:03

回答

1

我想我已經想通了 - 這是因爲屬性和方法的區別。它是觸發攔截器的get_方法,並且沒有使用父屬性的屬性進行修飾。

+0

是否有解決方法? – danyolgiax 2013-01-23 15:56:25

4

嘗試Attribute.GetCustomAttribute(...)靜態方法。這很奇怪,但這兩種方法有時會出於某種奇怪的原因返回不同的結果。

+0

是的,這就像一個魅力。謝謝! – 2010-04-01 19:36:13

+0

感謝隊友,我今天遇到了這個bug,並且正在去香蕉,直到你的帖子保存了一天。正如你所說,靜態方法的工作原理,通用的GetCustomAttribute ()也是如此。不幸的是,後者只存在於.NET 4.5中。 – 2013-04-08 00:10:11

+0

剛剛看到,http://msdn.microsoft.com/en-us/library/dwc6ew1d%28v=vs.110%29.aspx指出_「此方法忽略屬性和事件的繼承參數。要搜索繼承鏈屬性和事件的屬性,使用Attribute.GetCustomAttributes方法的適當重載。「_非常不一致的設計恕我直言。 – 2013-04-08 00:30:15

3

嘗試

private static Attribute getMyCustomAttribute(IInvocation invocation) 
{ 
    var methodInfo = invocation.MethodInvocationTarget; 
    if (methodInfo == null) 
    { 
     methodInfo = invocation.Method; 
    } 
    return Attribute.GetCustomAttribute(methodInfo, typeof(MyCustomAttribute), true); 
} 
+1

var methodInfo = invocation.MethodInvocationTarget ?? invocation.Method; – Soren 2014-01-08 10:46:09