【问题标题】:Access custom attribute on method from Castle Windsor interceptor从 Castle Windsor 拦截器访问方法的自定义属性
【发布时间】:2019-08-14 17:14:49
【问题描述】:

我正在尝试访问应用于城堡拦截器中的方法的自定义属性,例如:

[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
        }
    }
}

调用方法时拦截器触发正常,但此代码未返回自定义属性。我怎样才能做到这一点?

【问题讨论】:

  • 您使用的是什么版本的 DynamicProxy?

标签: c# castle-windsor interceptor castle-dynamicproxy


【解决方案1】:

为此尝试Attribute.GetCustomAttribute(...) 静态方法。这很奇怪,但这两种方法有时会出于某种奇怪的原因返回不同的结果。

【讨论】:

  • 谢谢伙计,我今天遇到了这个错误,并且一直在努力,直到你的帖子挽救了一天。正如您所说,静态方法有效,通用GetCustomAttribute<type>() 也有效。不幸的是,后者仅存在于 .NET 4.5 中。
  • 刚刚看到msdn.microsoft.com/en-us/library/dwc6ew1d%28v=vs.110%29.aspx 声明 “此方法忽略属性和事件的继承参数。要在继承链中搜索属性和事件的属性,请使用 Attribute 的适当重载.GetCustomAttributes 方法。” 恕我直言,设计非常不一致。
【解决方案2】:

试试

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

【讨论】:

  • var methodInfo = invocation.MethodInvocationTarget ??调用.方法;
【解决方案3】:

我想我已经弄清楚了——这是因为属性和方法之间的差异。触发拦截器的是get_方法,这个没有用父属性的属性修饰。

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 2011-02-26
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多