Martijn Veken


Just having
some fun with .NET

Adding a Policy Injection extension to Unity - Part III

I got a request to update the policy injection extension sample from my previous post to Unity 1.1. There are not that many differences but here is the updated code:

    5 namespace UnityHelpers.PolicyInjection
    6 {
    7     public class PolicyInjectionStrategy : BuilderStrategy
    8     {
    9         public override void PreBuildUp( IBuilderContext context )
   10         {
   11             IBuildKey buildKeyTo   = context.BuildKey as IBuildKey;
   12             IBuildKey buildKeyFrom = context.OriginalBuildKey as IBuildKey;
   13 
   14             if( buildKeyFrom != null && buildKeyFrom.Type != null && buildKeyFrom.Type.IsInterface )
   15             {
   16                 context.Existing = Wrap( context.Existing, buildKeyFrom.Type );
   17             }
   18 
   19             else if( buildKeyTo != null && buildKeyTo.Type != null && buildKeyTo.Type.IsMarshalByRef )
   20             {
   21                 context.Existing = Wrap( context.Existing, buildKeyTo.Type );
   22             }
   23 
   24             base.PreBuildUp( context );
   25         }
   26 
   27 
   28         private static object Wrap( object existing, Type t )
   29         {
   30             if( existing != null )
   31             {
   32                 existing = (new PolicyInjectorFactory()).Create().Wrap( existing, t );
   33             }
   34 
   35             return existing;
   36         }
   37     }

The ITypeBasedBuildKey is now replaced by IBuildKey in lines 11 and 12.

The code of the PolicyInjectionExtension class also changed a little bit:

    4 namespace UnityHelpers.PolicyInjection

    5 {

    6     public class PolicyInjectionExtension : UnityContainerExtension

    7     {

    8         protected override void Initialize()

    9         {

   10             Context.Strategies.AddNew<PolicyInjectionStrategy>(UnityBuildStage.PostInitialization);

   11         }

   12     }

   13 }

In the following thread on CodePlex a forum member states that the Builder Context is always null in the prebuild-up stage. I'm not experiencing this, but if you do his code solves your problem.

kick it on DotNetKicks.com AddThis Social Bookmark Button

Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 8 and 1 and type the answer here: