Unity - loadConfiguration, how to resolve only those configured

馋奶兔 提交于 2019-12-23 04:45:22

问题


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


回答1:


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?



来源:https://stackoverflow.com/questions/18369835/unity-loadconfiguration-how-to-resolve-only-those-configured

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!