Welcome to the Coach Factor blog. Here you will find all of our ideas on software development. Subscribe at http://blog.nventive.net.
In part 1 and part 2, we briefly explored what was Unity. In this part, we’ll introduce the subject of interception.
In releases prior to 4.1 of Enterprise Library, interception was something provided by the “Policy Injection Application Block”. One of the big moves for 4.1 was to refactor the functionality into Unity, and modify PIAB to be a facade (easier to use interface) over Unity.
But the question remains, what is interception. Interception relates to a programming technique called AOP (Aspect Oriented Programming) and deals with things that are mostly non-functional (logging, exception handling, security, caching…). This said, you would use interception to perform security checks (for example) in a transparent way while calling a target method on a target object.
1 public class AccountingService
2 {
3 public virtual void Deposit(decimal amount)
4 { }
5 }
6
7 public class FormController
8 {
9 public void DoSomething()
10 {
11 IUnityContainer container = GetContainer();
12
13 var accountingService = container.Resolve<AccountingService>();
14
15 accountingService.Deposit(50.0m);
16 }
17 }
From this example, you see that we are resolving the AccountingService class through the container, and then calling the Deposit method. Let’s see how we implemented GetContainer() to account for interception.
1 public IUnityContainer GetContainer()
3 IUnityContainer container = new UnityContainer();
4 container.AddNewExtension<Interception>();
5
6 //define how to intercept
7 container.Configure<Interception>()
8 .SetDefaultInterceptorFor<AccountingService>(new VirtualMethodInterceptor());
9
10 //create policy
11 container.Configure<Interception>()
12 .AddPolicy("SecurityPolicy")
13 .AddMatchingRule(new TypeMatchingRule(typeof(AccountingService)))
14 .AddCallHandler<SecurityCallHandler>();
15
16 return container;
From this example, you cann see that we are asking Unity to intercept AccountService types using the VirutalMethodInterceptor, and to define a policy, that will be applied to types of type AccountingService who will invoke the SecurityCallHandler. The SecurityCallHandler is defined as such:
1 public class SecurityCallHandler : ICallHandler
3 #region ICallHandler Members
4
5 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
6 {
7 throw new InvalidOperationException("You can't do that.");
8 //return getNext.Invoke().Invoke(input, getNext);
9 }
10
11 public int Order
12 {
13 get { return 0; }
14 set { }
15 }
16
17 #endregion
18 }
The call handler is what performs you non-functional code. This is where you would put your logging, validation, security, caching code, which would transparently wrap the object being intercepted.
More on the possibilities in part 4.
2008 nVentive. All rights reserved.