0

What I am trying to achieve: Have Unity load the mappings from a configuration file, then in source code resolve the types which were loaded from said configuration file

App.Config

<register type="NameSpace.ITill, ExampleTightCoupled" mapTo="NameSpace.Till, NameSpace" />
<register type="NameSpace.IAnalyticLogs, NameSpace" mapTo="NameSpace.AnalyticLogs, NameSpace" />

Code

IUnityContainer container;
container = new UnityContainer();

// Read interface->type mappings from app.config
container.LoadConfiguration();

// Resolve ILogger - this works
ILogger obj = container.Resolve<ILogger>();

// Resolve IBus - this fails
IBus = container.Resolve<IBus>();

Issue: Sometimes IBus will be defined in the App.config, and sometimes it will not be there. When I try and resolve an interface/class and it does not exist I get an exception.

Can someone educate me here?

Thanks, Andrew

andrewb
  • 2,995
  • 7
  • 54
  • 95
  • 1
    Prevent coming in this situation all together. If `IBus` is an optional dependency, create and register a [Null Object Pattern](http://en.wikipedia.org/wiki/Null_Object_pattern) implementation (an empty implementation that is effectively a no-op). This prevents you from having to complicate your application logic. – Steven Aug 22 '13 at 06:50

1 Answers1

2

What version of Unity are you using? In v2+ there is an extension method:

public static bool IsRegistered<T>(this IUnityContainer container);

so you can do

if (container.IsRegistered<IBus>())
    IBus = container.Resolve<IBus>();

An extension method would make this nicer

public static class UnityExtensions
{
    public static T TryResolve<T>(this IUnityContainer container)
    {
        if (container.IsRegistered<T>())
            return container.Resolve<T>();

        return default(T);
    }
}

// TryResolve returns the default type (null in this case) if the type is not configured
IBus = container.TryResolve<IBus>();

Also check out this link: Is there TryResolve in Unity?

Community
  • 1
  • 1
Hack
  • 1,408
  • 10
  • 13
  • 3
    One [big warning](https://unity.codeplex.com/discussions/392550) about the `IsRegistered` method: It is only meant for debugging because it is notoriously slow! It has a performance characteristic of O(n) and can completely drown the performance of your application. – Steven Aug 22 '13 at 06:46
  • TryResolve doesn't always return null -- it is returning the default value for the type (which is null for reference types). But if resolving an int, for example, 0 will be returned. Also, it might be nice to align with the Unity Resolve method and support ResolverOverrides as well as the name override. – Randy Levy Aug 22 '13 at 14:41
  • Yeah I'm aware it'll return the default type, I meant it'll return null for IBus. I'll update the comment to reflect that. – Hack Aug 22 '13 at 23:10