问题描述
我想实现:具有单位从配置文件加载的映射,然后在源代码中解决这是从上述配置文件
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
应用程序加载的类型.CONFIG
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>();
问题:有时下iBus将在App.config中定义的,有时它会不会在那里。当我尝试解决一个接口/类,它不存在,我得到一个异常。
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.
有人能教我吗?
谢谢,
安德鲁
Thanks,Andrew
推荐答案
您正在使用什么版本的Unity?在V2 +有一个扩展方法:
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>();
另外,请查阅此链接:
这篇关于团结 - loadConfiguration,如何解决只有那些配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!