C# 在统一中有解决问题的方法吗?
如果C# 在统一中有解决问题的方法吗?,c#,unity-container,ioc-container,C#,Unity Container,Ioc Container,如果Resolve失败,我如何使Unity不抛出ResolutionFailedException 是否有类似于TryResolve var container=newunitycontainer(); var foo=container.TryResolve(); Assert.IsNull(foo); 它似乎缺少此功能。显示了在try/catch块中封闭Resolve方法以实现它的示例 public object TryResolve(Type type) { object reso
Resolve
失败,我如何使Unity不抛出ResolutionFailedException
是否有类似于TryResolve
var container=newunitycontainer();
var foo=container.TryResolve();
Assert.IsNull(foo);
它似乎缺少此功能。显示了在try/catch块中封闭Resolve方法以实现它的示例
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;
}
}
}
公共静态类UnityExtensions
{
公共静态TryResolve(此UnityContainer容器)
T:在哪里上课
{
尝试
{
返回(T)容器。解析(类型(T));
}
捕获(例外)
{
返回null;
}
}
}
这是codeplex站点上的一个问题,您可以在这里找到代码(查看该线程的底部,他们已经制作了一个扩展方法…非常方便)
您可以使用如下代码:
if (container.CanResolve<T>() == true)
{
try
{
return container.Resolve<T>();
}
catch (Exception e)
{
// do something else
}
}
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);
}
还要注意的是,如果您正在使用,您可以使用新方法,它也是。在Prism Unity 5中,他们提出了TryResolve函数,该函数已包含在名称空间Microsoft.Practices.Prism.UnityExtensions中 请浏览此链接以供参考。
IComponent component=null;
IComponent component= null;
if (c.IsRegistered<IComponent>(registrationName))
{
component= c.Resolve<IComponent>(registrationName);
}
return component;
如果(c.IsRegistered(注册名称))
{
组件=c.Resolve(注册名称);
}
返回组件;
谢谢你的回答。我不确定我的问题是否清楚,但你的答案正是我想要的。实用但昂贵。捕获异常并返回null不是一种好的做法。扩展的好方法,但不是尝试捕获,而是使用成本较低的IsRegistered方法。IsRegistered方法之一:它只用于调试,因为它的速度非常慢!它具有O(n)的性能特征,可以完全淹没应用程序的性能。
IComponent component= null;
if (c.IsRegistered<IComponent>(registrationName))
{
component= c.Resolve<IComponent>(registrationName);
}
return component;