How can I determine if a type is configured given a container?

Jan 8, 2010 at 3:36 PM

I have a service locator that wraps the Unity container.

I'm trying to add a method to my service locator wrapper that allows the testing of a type/key combination to see if it is configured.

The wrapper would be called like:


Is this information possible given a unity container? Will I need implement a container extension?

I'm looking for the most direct route to this solution,


Peter Stephens

Jan 8, 2010 at 10:36 PM

This is implemented directly in Unity 2.0. For 1.2, you'd need a container extension. You need to track the Registering events as they go by and record which ones happened.



Jan 9, 2010 at 12:13 AM

Thanks for the quick reply!

The extension route was the way I chose. I first thought I would have to handle the Registering event on the ExtensionContext. This would work as you suggest.

Then I saw this code in UnityBootstrapperExtension.cs in Prism:


        public static bool IsTypeRegistered(IUnityContainer container, Type type)
            UnityBootstrapperExtension extension = container.Configure<UnityBootstrapperExtension>();
            if (extension == null)
                //Extension was not added to the container.
                return false;
            IBuildKeyMappingPolicy policy = extension.Context.Policies.Get<IBuildKeyMappingPolicy>(new NamedTypeBuildKey(type));
            return policy != null;

Does this routine have too much reliance on the internal workings of Unity? I agree that handling the Registering event would work but this was easier to implement!


Jan 9, 2010 at 5:34 AM

That would work as well. It does make a lot more assumptions about the internals, but you're pretty much guaranteed that that particular design isn't going to change soon. All I would do is make sure to encapsulate that logic in a method, and if / when you update to Unity 2.0 you replace the code with the core, supported container.IsRegistered API instead.