无法使用DynamicProxy在Interceptor中检索CustomAttributes

Pau*_*aul 1 .net castle castle-dynamicproxy

我目前正在使用Castle DynamicProxy实现拦截器.我要求拦截器在我的服务层方法上获取一些自定义属性,但是invocation.Method.GetCustomAttributes什么都不返回.我可能做错什么?

截获方法:

 [Transaction()]
 [SecurityRole(AuthenticationRequired = false, Role = SystemRole.Unauthorised)]
 public virtual void LoginUser(out SystemUser userToLogin, string username)
 {
     ...
 }
Run Code Online (Sandbox Code Playgroud)

拦截器:

// Checks that a security attribute has been defined
foreach (SecurityRoleAttribute role in invocation.Method.GetCustomAttributes(typeof(SecurityRoleAttribute), true))
{
    if (!securityAttributeDefined)
        securityAttributeDefined = true;
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

Attribute.GetCustomAttribute(invocation.Method, typeof(SecurityRoleAttribute), true);
Run Code Online (Sandbox Code Playgroud)

更新:

可能是配置问题.配置代码如下:

InterceptorsInstaller:

    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
         container.Register(
            Component.For<LoggingInterceptor>()
            .Named("LoggingInterceptor"));

         container.Register(
            Component.For<SecurityInterceptor>()
            .Named("SecurityInterceptor"));

         container.Register(
            Component.For<ValidationInterceptor>()
            .Named("ValidationInterceptor"));
    }
Run Code Online (Sandbox Code Playgroud)

的ServiceInstaller:

    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        string[] interceptors = {"LoggingInterceptor", "SecurityInterceptor"};

        container.Register(AllTypes.FromAssemblyContaining<BaseService>().Pick()
                            .If(Component.IsInSameNamespaceAs<LoginService>())
                            .Configure(c => c
                                               .LifeStyle.Transient
                                               .Interceptors(interceptors))
                            .WithService.DefaultInterface());
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用Castle 2.5.2/.Net 3.5.

谢谢,

保罗

Pau*_*aul 5

事实证明这是因为代理是一个接口代理.获取方法调用目标,然后从methodInfo获取属性修复它:

    MethodInfo methodInfo = invocation.MethodInvocationTarget; 
    if (methodInfo == null) { 
        methodInfo = invocation.Method; 
    }
Run Code Online (Sandbox Code Playgroud)