andrewb
andrewb

Reputation: 3095

Unity - loadConfiguration, how to resolve only those configured

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

Upvotes: 0

Views: 2817

Answers (1)

Hack
Hack

Reputation: 1408

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?

Upvotes: 2

Related Questions