Creating your own method interceptors - TylerBrinks/Snap GitHub Wiki
Let’s say you want to decorate methods to take action when you encounter an unhandled exception. There are two classes that you’ll need to create in order to intercept methods. Let’s start with the interceptor.
The following example of a sample error handler interceptor
// Your interceptor is derived from Snap.MethodInterceptor public class HandleErrorInterceptor : MethodInterceptor { // InterceptMethod is where your logic goes. Notice that you're passed in a Castle IInvocation // as well as the MethodBase and the method's attribute. You can use reflection on the method // where necessary. You can also interrogate your attribute for your own custom properties. public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute) { try { // Allow Castle to attempt the method call invocation.Proceed(); } catch { // Do something useful here. } } }
It’s as simple as that. You only have to override InterceptMethod to get started.
In the configuration examples this interceptor is bound to a particular attribute to determine which methods to intercept. Let’s build an attribute that you can use to decorate your methods.
public class HandleErrorAttribute : MethodInterceptAttribute { }
That’s it. Nothing more. Of course, you can add custom properties if you need, but this is all that’s necessary to work.
Here’s a slightly more advanced example that supports constructor parameters. Keep in mind that you’ll have to cast the attribute, as passed in to the InterceptMethod, as the target type. In this case you’d cast the attribute as a HandleErrorAttribute, and have full access to all properties, methods, etc…
// Attribute with constructor parameters public class HandleErrorAttribute : MethodInterceptAttribute { public HandleErrorAttribute(bool someProperty) { this.SomeProperty = someProperty; } public bool SomeProperty { get; set; } }
Happy coding!