What if Extension Strategy Needs Access to Container?

Mar 15, 2008 at 2:58 PM
I have an extension that I created last night, but the strategy it adds to the container needs access to the container in order to get a type that should be loaded into the container. In other words, the strategy needs to do the equivalent of UnityContainer.Resolve<T>().

This brings up a whole bunch of questions concerning whether extensions should access ( be dependent on ) the container, how they access the container, etc?

I tried passing the container via a policy and using it in the strategy, and of course, this just ended up with an infinite loop :) hehe...

I then decided that instead of passing the container via a policy I would just do the UnityContainer.Resolve<T> within the Initialize Method of the Extension and pass in the typemapping via the policy. This works, but then the extension has a dependency on the fact that the typemapping must be added before the extension.

There is probably some basic logic about extensions I am missing here. Any help would be appreciated on how strategies get access to the container they are within in order to use those services.

Best Regards,

Dave
Mar 15, 2008 at 7:10 PM
You don't need to be dependent on the container; the container is just a facade over the strategy chain and policy list.

What you need to do is recursively invoke the strategy chain. Look at the code for the dependency resolvers for a example.

Basically, what you do is clone the build context, then invoke the strategy chain again:

IBuilderContext newContext = context.CloneForNewBuild(newBuildKey, null);
object myNewObject = newContext.Strategies.ExecuteBuildUp(newContext);

And there you go.
Mar 16, 2008 at 11:31 PM
Perfect. Thanks for you help, Chris.

Your code and the code in the NamedTypeDependencyResolverPolicy were exactly what I needed.

Best Regards,

Dave