Where / When to Use Interceptors
Take a look at the previous application you developed and study the code. Look for code that is often duplicated at the beginning or end of methods and properties. This is code that you can consider moving from all of these methods to an interceptor. For example, I noticed that many of my MVC actions doing input validation do this with the same pairs of lines of code:
if (!ModelState.IsValid) return View(model);
This is code that could potentially be moved to an interceptor (perhaps in this case an MVC filter). Does the cost of writing and applying a filter increase the cost of this duplicate code? (2 lines of code multiply the number of controller actions using this). In this case, perhaps not. However, there are other situations where the advantage of using an interceptor will be greater.
Here is a list of some situations where I assume that this type of code duplication can occur, that is, scripts that smell like they could use sniffers :
- Input validation (as shown above).
- Debug Logs You can write an interceptor that records the input and output of each method call.
- Stream Sync. . Your question is about web applications, but if you are developing a Windows application with an MVP style representation, you can use an interceptor that ensures that all method calls are synchronized with the user interface thread.
- Database Operations. Most of my database transaction code is as follows:
using (var transaction = Session.BeginTransaction()) { // ... do some work that is unique to this method ... transaction.Commit(); }
Whether the above examples are good candidates for interceptors depends on the unique subtleties of your application. This list, of course, is not exhaustive, and cannot be. The possible applications of interceptors are as diverse as the applications you write.
How to use interceptors
I can think of three main places where you could use interceptor objects: Controllers, Services, and Domains.
- With an MVC controller , it makes sense to go ahead and use MVC filters .
- For the mid-range service that you pull from your IoC container, filters are not an option (because it is not a controller), so you should use the intercept functions of your IoC container .
- For your domain objects , which you usually either create directly using the constructor (if it is a new object), or choose from your ORM selection (if it is an existing object), you will need to use the factory object instead of the constructor and instruct your ORM how to use factory .
The detailed details on how to accomplish all this will depend on which tools you use.
Daniel Schilling
source share