问题
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
回答1:
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;
}
回答2:
Your interceptor code is fine, but you're registering it wrong. What you wrote means “if I ask you for IInterceptor
, give me SecurityInterceptor
”. You want to say “intercept calls to the class that contains LoginUser()
(let's call it Foo
) using SecurityInterceptor
”. Translated into C#, it looks like this:
container.Register(Component.For<Foo>().Interceptors<SecurityInterceptor>());
container.Register(Component.For<SecurityInterceptor>().Named("SecurityInterceptor"));
来源:https://stackoverflow.com/questions/6238012/cannot-retrieve-customattributes-in-interceptor-using-dynamicproxy