How to get UnityContainer in BuilderStrategy

Aug 30, 2008 at 11:39 AM
Edited Aug 30, 2008 at 11:43 AM

I'm creating a logger strategy for the CompositeWPF to aid in debugging (the extension will only be added when required).   Before I blog the topic I want to ensure I have the most efficient method of obtaining a Unity container reference from within the BuilderStrategy - is there an easier way?



    public class LoggerStrategy : BuilderStrategy


        public ILogger Logger { get; set; }


        public LoggerStrategy() { }


        public override void PreBuildUp(IBuilderContext context)


            // Prevent stack overflow

            if (((NamedTypeBuildKey)context.OriginalBuildKey)




            // Obtain logger reference

            Logger = (ILogger) GetContainer(context).Resolve<ILogger>();


            NamedTypeBuildKey buildKey = (NamedTypeBuildKey)

                buildKey.Type.Name), Category.Info, Priority.None);



        protected IUnityContainer GetContainer(IBuilderContext context)


            object lifetimeManager = context.Lifetime
                .FirstOrDefault(key =>




            IUnityContainer container = (IUnityContainer)



            return container;




FYI, Info on tool used to copy/paste code from VS->HTML HERE

Sep 1, 2008 at 8:14 PM
Can I safely assume you've done something like: 


before you run this?

I see two issues here. The first is that iterating over the contents of the lifetime container isn't going to be the fastest in the world. The second is that you're seriously violating encapsulation. What if somebody had done:

container.RegisterInstance(container, new ExternallyControlledLifetimeManager())


The best way to do this is to use a recursive buildup:

IBuilderContext clone = context.CloneForNewBuild(NamedTypeBuildKey.Make<IUnityContainer>(), null);
return (IUnityContainer)clone.Existing;

You might be able to eke out a few more microseconds by going straight to the lifetime manager:

ILifetimePolicy lifetime = context.Policies.Get<ILifetimePolicy>(NamedTypeBuildKey.Make<IUnityContainer>());
return (IUnityContainer)lifetime.GetValue();

(be sure to add appropriate null checks).

Of the two, I'd strongly recommend the former. That way is much less vulnerable to quirks in the container configuration.

Now, having said that, why do you need to go through the container? You could just do the recursive buildup on the ILogger directly:

private ILogger GetLogger(IBuilderContext context)
    IBuilderContext clone = context.CloneForNewBuild(NamedTypeBuildKey.Make<ILogger>(), null);
    return (ILogger)clone.Existing;

This is identical to what you've got above without the extra overhead of resolving the container first.