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
3 public override void PreBuildUp( IBuilderContext context )
5 ITypeBasedBuildKey buildKeyTo = context.BuildKey as ITypeBasedBuildKey;
6 ITypeBasedBuildKey buildKeyFrom = context.OriginalBuildKey as ITypeBasedBuildKey;
8 if( buildKeyFrom != null && buildKeyFrom.Type != null && buildKeyFrom.Type.IsInterface )
10 context.Existing = Wrap( context.Existing, buildKeyFrom.Type );
12 else if( buildKeyTo != null && buildKeyTo.Type != null && buildKeyTo.Type.IsMarshalByRef )
14 context.Existing = Wrap( context.Existing, buildKeyTo.Type );
17 base.PreBuildUp( context );
20 private static object Wrap(object existing, Type t)
22 if (existing != null)
24 existing = (new PolicyInjectorFactory()).Create().Wrap(existing, t);
26 return existing;
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.