views:

259

answers:

2

Can I test if a type has been registered in a Unity container without calling for a Resolve and trapping the exception?

+1  A: 

Your only other option (currently) is to use ResolveAll<T>() and enumerate the results.

Mitch Wheat
Suspected so, thanks
johnc
+2  A: 

Unity 2.0 will have an IsRegistered method that you can use to find out if a type has been registered in the container.

The Beta1 of Unity 2.0 is available on Codeplex as of Feb 10th. See the release notes and download it here; http://unity.codeplex.com/wikipage?title=Unity2%20Beta1

UPDATE:

Downloaded and tested Unity 2.0 beta 1 on Feb 27th 2010, and it's by far production ready yet. If you're using Unity 1.2 today you will have to do some major work to get Unity 2.0 working because of the incomplete(?) IUnityContainer interface. So if you want to have the IsRegistered method working today, you can make an extension method like this:

public static class UnityContainerExtensions
{
    public static bool IsRegistered<T>(this IUnityContainer container)
    {
        try
        {
            container.Resolve<T>();
            return true;
        }
        catch
        {
            return false;
        }
    }
}

Note that I'm not using ResolveAll here. The reason for this is that ResolveAll will not return the default (un-named) registration as stated in the Unity docs:

This method is useful if you've registered multiple types with the same Type but different names.

Be aware that this method does NOT return an instance for the default (unnamed) registration.

Kjetil Klaussen
Thanks for the update.
johnc