Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there TryResolve in Unity?

How can I make Unity not to throw ResolutionFailedException if Resolve fails?

Is there something like TryResolve<IMyInterface>?

var container = new UnityContainer();
var foo = container.TryResolve<IFoo>();
Assert.IsNull(foo);
like image 278
Vadim Avatar asked May 18 '09 17:05

Vadim


4 Answers

Also note that, if you're using Unity 2.0 you can use the new IsRegistered() method and it's generic version as well.

like image 135
Bryan Ray Avatar answered Nov 14 '22 12:11

Bryan Ray


This has been an issue on the codeplex site, you can find the code here (look at the bottom of that thread and they have made an extension method...very handy)

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

and the you can use code like this:

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

CanResolve is that extension method. I'm actually registering that extension upon creation of the container...something like this:

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);        
}
like image 36
Johan Leino Avatar answered Nov 14 '22 12:11

Johan Leino


It seems that it lacks this feature. This article shows the example of enclosing Resolve method in the try/catch block to implement it.

public object TryResolve(Type type)
{
    object resolved;

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

    return resolved;
}
like image 3
bbmud Avatar answered Nov 14 '22 14:11

bbmud


This is not available in the current release. However, you can always "roll your own" using extension methods in C# 3. Once Unity supports this, you can omit or update the extension method.

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;
        }
    }
}
like image 2
LBushkin Avatar answered Nov 14 '22 14:11

LBushkin