Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a Type has been registered in Unity

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

like image 500
johnc Avatar asked Jan 25 '09 01:01

johnc


2 Answers

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.

like image 62
Kjetil Klaussen Avatar answered Oct 16 '22 00:10

Kjetil Klaussen


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

like image 21
Mitch Wheat Avatar answered Oct 16 '22 00:10

Mitch Wheat