如何使用新的Unity 5.0.0 Resolve()方法解析类的实例?
在Unity 4.0.1中,我使用SettingsContext
解决了下面给出的示例。但这不再适用。
我认为这是为Resolve提供第二个论点的问题,但我不确定如何。
var _unity = UnityConfig.GetConfiguredContainer();
var _settings = _unity.Resolve<SettingsContext>();
将UnityConfig类定义为
public class UnityConfig
{
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
public static void RegisterTypes(IUnityContainer unity)
{
//all the unity.RegisterType calls
}
}
答案 0 :(得分:1)
最后,让section对象配置容器。
var c = new UnityContainer();
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(c);
var ss = c.Resolve<IStorageSystem>();
对于 app | web.config ,请务必引用更新的类型定义(请参阅程序集)。
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="FileBox.IStorageSystem, FileBox" mapTo="FileBox.StorageSystem.Local.LocalFileSystem, FileBox" >
<constructor>
<param name="root">
<value value =""/>
</param>
</constructor>
</register>
</container>