Adding a Policy Injection extension to Unity - Part II
Yesterday I blogged about on how to add a Policy Injection extension to Unity. To do this, I had to modify some of the code of both Unity and ObjectBuilder2 to get all the references I needed. Today Francois Tanguay pointed me to the new drop of Unity released on Monday.
A couple of improvements have been made in this drop and one of these is the availbility of the original build key. This is the key before any mapping has occured and just what I need to create my extension without making modifications to Unity and ObjectBuilder2.
The code of the extension is now:
1 public class PolicyInjectionStrategy : BuilderStrategy
2 {
3 public override void PreBuildUp( IBuilderContext context )
4 {
5 ITypeBasedBuildKey buildKeyTo = context.BuildKey as ITypeBasedBuildKey;
6 ITypeBasedBuildKey buildKeyFrom = context.OriginalBuildKey as ITypeBasedBuildKey;
7
8 if( buildKeyFrom != null && buildKeyFrom.Type != null && buildKeyFrom.Type.IsInterface )
9 {
10 context.Existing = Wrap( context.Existing, buildKeyFrom.Type );
11 }
12 else if( buildKeyTo != null && buildKeyTo.Type != null && buildKeyTo.Type.IsMarshalByRef )
13 {
14 context.Existing = Wrap( context.Existing, buildKeyTo.Type );
15 }
16
17 base.PreBuildUp( context );
18 }
19
20 private static object Wrap(object existing, Type t)
21 {
22 if (existing != null)
23 {
24 existing = (new PolicyInjectorFactory()).Create().Wrap(existing, t);
25 }
26 return existing;
27 }
28 }
The BuilderStrategy base class now also has PreBuildUp and PostBuildUp methods to override. The PreBuildUp methods are excuted through the chain in a forward direction, just like the former BuildUp method. The PostBuildUp methods are called in reverse order when all PreBuildUp methods have been executed.