Search code examples
.netcastlecastle-dynamicproxy

Cannot retrieve CustomAttributes in Interceptor using DynamicProxy


I'm currently implementing Interceptors using Castle DynamicProxy. I require the interceptor to pick up some custom attributes on my service layer method, but invocation.Method.GetCustomAttributes returns nothing. Anything I could be doing wrong?

Intercepted Method:

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

Interceptor:

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

I've also tried:

Attribute.GetCustomAttribute(invocation.Method, typeof(SecurityRoleAttribute), true);

Update:

May be a configuration issue. The config code is as follows:

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"));
    }

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());
    }

I'm Using Castle 2.5.2/.Net 3.5.

Thanks,

Paul


Solution

  • Turns out it was because the proxy is an interface proxy. Getting the method invocation target, then getting the attributes from methodInfo fixed it:

        MethodInfo methodInfo = invocation.MethodInvocationTarget; 
        if (methodInfo == null) { 
            methodInfo = invocation.Method; 
        }