测试类型是否已在Unity中注册 [英] Testing if a Type has been registered in Unity

查看:68
本文介绍了测试类型是否已在Unity中注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不调用解析和捕获异常的情况下测试类型是否已在Unity容器中注册?

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

推荐答案

Unity 2.0将具有IsRegistered方法,可用于查找容器中是否已注册类型.

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

Unity 2.0的Beta1自2月10日起可在Codeplex上使用.请参阅发行说明并在此处下载. http://unity.codeplex.com/wikipage?title=Unity2%20Beta1

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

更新:

2010年2月27日下载并测试了Unity 2.0 beta 1,到目前为止,它已经可以生产了.如果今天使用的是Unity 1.2,则由于IUnityContainer接口不完整(?),必须使Unity 2.0正常工作.因此,如果您想让IsRegistered方法在今天工作,可以制作这样的扩展方法:

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;
        }
    }
}

请注意,我在这里不使用ResolveAll.原因是ResolveAll不会返回Unity文档中所述的默认(未命名)注册:

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.

这篇关于测试类型是否已在Unity中注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆