使用 Castle Windsor IInterceptor 拦截属性

发布于 2024-09-04 03:23:41 字数 1055 浏览 5 评论 0 原文

有没有人有关于使用 Castle DynamicProxy 拦截属性的更好方法的建议?

具体来说,我需要要拦截的 PropertyInfo,但它不是直接在 IInvocation 上,所以我要做的是:

public static PropertyInfo GetProperty(this MethodInfo method)
{
    bool takesArg = method.GetParameters().Length == 1;
    bool hasReturn = method.ReturnType != typeof(void);
    if (takesArg == hasReturn) return null;
    if (takesArg)
    {
        return method.DeclaringType.GetProperties()
            .Where(prop => prop.GetSetMethod() == method).FirstOrDefault();
    }
    else
    {
        return method.DeclaringType.GetProperties()
            .Where(prop => prop.GetGetMethod() == method).FirstOrDefault();
    }
}

然后在我的 IInterceptor 中:

public void Intercept(IInvocation invocation)
{
    bool doSomething = invocation.Method
                                 .GetProperty()
                                 .GetCustomAttributes(true)
                                 .OfType<SomeAttribute>()
                                 .Count() > 0;

}

Does anyone have a suggestion on a better way to intercept a properties with Castle DynamicProxy?

Specifically, I need the PropertyInfo that I'm intercepting, but it's not directly on the IInvocation, so what I do is:

public static PropertyInfo GetProperty(this MethodInfo method)
{
    bool takesArg = method.GetParameters().Length == 1;
    bool hasReturn = method.ReturnType != typeof(void);
    if (takesArg == hasReturn) return null;
    if (takesArg)
    {
        return method.DeclaringType.GetProperties()
            .Where(prop => prop.GetSetMethod() == method).FirstOrDefault();
    }
    else
    {
        return method.DeclaringType.GetProperties()
            .Where(prop => prop.GetGetMethod() == method).FirstOrDefault();
    }
}

Then in my IInterceptor:

public void Intercept(IInvocation invocation)
{
    bool doSomething = invocation.Method
                                 .GetProperty()
                                 .GetCustomAttributes(true)
                                 .OfType<SomeAttribute>()
                                 .Count() > 0;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我恋#小黄人 2024-09-11 03:23:41

一般情况下这是不可用的。 DynamicProxy 拦截方法(包括 getter 和 setter),并且不关心属性。

您可以通过设置拦截器 IOnBehalfAware 来稍微优化此代码(请参阅 此处)并预先发现方法->属性映射。

Generally this is not available. DynamicProxy intercepts methods (incl. getters and setters), and it does not care about properties.

You could optimize this code a bit by making the interceptor IOnBehalfAware (see here) and discovering the method->property mapping upfront.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文