Unity에는 TryResolve가 있습니까?
-
22-08-2019 - |
문제
어떻게 통일을 던지지 않도록 할 수 있습니까? 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);
}
다른 팁
이 기능이 부족한 것 같습니다. 이 기사 시도/캐치 블록의 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;
}
}
}
Prism Unity 5에서 그들은 tryresolve 네임 스페이스에 포함 된 함수 Microsoft.practices.prism.unityextensions.
이 링크를 살펴보십시오 https://msdn.microsoft.com/en-us/library/gg419013(v=pandp.50).aspx 참조.
제휴하지 않습니다 StackOverflow