我怎样才能让Unity不抛出 ResolutionFailedException 如果 Resolve 失败?

有没有类似的东西 TryResolve<IMyInterface>?

var container = new UnityContainer();
var foo = container.TryResolve<IFoo>();
Assert.IsNull(foo);
有帮助吗?

解决方案

这是 codeplex 网站上的一个问题,您可以在这里找到代码(查看该线程的底部,他们制作了一个扩展方法......非常方便)

http://unity.codeplex.com/Thread/View.aspx?ThreadId=24543

你可以使用这样的代码:

if (container.CanResolve<T>() == true)
{
    try
    {
        return container.Resolve<T>();
    }
    catch (Exception e)
    {
        // do something else
    }
}

CanResolve 就是那个扩展方法。我实际上是在创建容器时注册该扩展......如下所示:

private void CreateContainer()
{
    ExeConfigurationFileMap map = new ExeConfigurationFileMap();

    map.ExeConfigFilename = // path to config file

    // get section from config code goes here

    IUnityContainer container = new UnityContainer();
    container.AddNewExtension<UnityExtensionWithTypeTracking>();
    section.Containers.Default.Configure(container);        
}

其他提示

另请注意,如果您使用 统一2.0 你可以使用新的 已登记() 方法及其 通用版本 以及。

好像缺少这个功能。 本文 显示了将 Resolve 方法包含在 try/catch 块中来实现它的示例。

public object TryResolve(Type type)
{
    object resolved;

    try
    {
        resolved = Resolve(type);
    }
    catch
    {
        resolved = null;
    }

    return resolved;
}

当前版本中不提供此功能。但是,您始终可以使用 C# 3 中的扩展方法“自行开发”。一旦 Unity 支持此功能,您就可以省略或更新扩展方法。

public static class UnityExtensions
{
    public static T TryResolve<T>( this UnityContainer container )
        where T : class
    {
        try
        {
            return (T)container.Resolve( typeof( T ) );
        }
        catch( Exception )
        {
            return null;
        }
    }
}

在 Prism Unity 5 中,他们提出了 尝试解决 已包含在命名空间中的函数 Microsoft.Practices.Prism.UnityExtensions.

请通过此链接 https://msdn.microsoft.com/en-us/library/gg419013(v=pandp.50).aspx 以供参考。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top