In googling I can't seem to find an example of intercepting event on a proxied type and it doesn't seem to be working for me. Is there a way I can do this (ie. use an IInterceptor when an event is invoked)?
Asked
Active
Viewed 1,383 times
2 Answers
2
I doubt it. Castle Dynamic Proxy works by intercepting the calls made on the proxy. Events are not made on the proxy. They're callbacks handled by the .NET framework.

PatrickSteele
- 14,489
- 2
- 51
- 54
-
2That is correct. With DP you can intercept methods, including event subscription and unsubscription, but that's it. – Krzysztof Kozmic Jun 04 '10 at 22:04
-
Thanks, my solution below accomplishes what I was looking for so this isn't necessary. – Jeff Jun 05 '10 at 20:26
2
I ended up using the ComponentCreated event, then adding a dynamic event handler with a DynamicMethod to accomplish what I wanted:
private static readonly MethodInfo internalPublishEventMethod =
typeof(EventPublisher).GetMethod("PublishEvent", BindingFlags.Static | BindingFlags.NonPublic);
private void Container_ComponentCreated(global::Castle.Core.ComponentModel model, object instance)
{
if (instance != null)
{
Type type = instance.GetType();
var eventPublisherAttribute = type.GetAttribute<EventPublisherAttribute>();
if (eventPublisherAttribute != null)
{
foreach (EventInfo ei in type.GetEvents())
{
if (eventPublisherAttribute.PublishAllEvents || ei.GetCustomAttributes(typeof(PublishedEventAttribute), false).Length > 0)
{
// emit an event handler
MethodInfo invoke = ei.EventHandlerType.GetMethod("Invoke");
Type[] parameters = invoke.GetParameters().Select(p => p.ParameterType).ToArray();
var method = new DynamicMethod(string.Empty, null, parameters, instance.GetType(),
true);
ILGenerator generator = method.GetILGenerator();
// sender
generator.Emit(OpCodes.Ldarg_0);
// args
generator.Emit(OpCodes.Ldarg_1);
// topic
generator.Emit(OpCodes.Ldstr, ei.Name);
generator.Emit(OpCodes.Call, internalPublishEventMethod);
generator.Emit(OpCodes.Ret);
Delegate d = method.CreateDelegate(ei.EventHandlerType);
ei.AddEventHandler(instance, d);
}
}
}
}
}
private static void PublishEvent(object sender, EventArgs e, string topic)
{
if (e != null)
{
// do stuff
}
}

Jeff
- 35,755
- 15
- 108
- 220
-
-
6 years later... event are wired to the Containers Kernel exposed by IKernelEvents. https://github.com/castleproject/Windsor/blob/master/docs/container-events.md – Konstantin Dec 06 '16 at 21:19