Unity – loadConfiguration,如何只解析那些配置的
我想要实现的目标:让Unity从配置文件加载映射,然后在源代码中解析从所述配置文件加载的类型
App.Config中
码
IUnityContainer container; container = new UnityContainer(); // Read interface->type mappings from app.config container.LoadConfiguration(); // Resolve ILogger - this works ILogger obj = container.Resolve(); // Resolve IBus - this fails IBus = container.Resolve();
问题:有时IBus将在App.config中定义,有时它不会在那里。 当我尝试解析一个接口/类并且它不存在时,我得到一个exception。
有人可以在这教育我吗?
谢谢,安德鲁
您使用的是什么版本的Unity? 在v2 +中有一个扩展方法:
public static bool IsRegistered(this IUnityContainer container);
所以你可以做到
if (container.IsRegistered()) IBus = container.Resolve ();
扩展方法会使这更好
public static class UnityExtensions { public static T TryResolve(this IUnityContainer container) { if (container.IsRegistered ()) return container.Resolve (); return default(T); } } // TryResolve returns the default type (null in this case) if the type is not configured IBus = container.TryResolve();
另请查看此链接: Unity中是否有TryResolve?