以下代码适用于版本3.5.1404,但不再适用于版本5.0.1。通过NuGet获得最新的参考资料:
web.config中的我有:
using Microsoft.Practices.Unity.Configuration;
using Unity;
namespace ACME.Core
{
public static class UnityCommon
{
static IUnityContainer _container;
/// <summary>
/// Returns the Common Unity Container from memory, reloads if not loaded first
/// </summary>
/// <param name="forceRefresh">Forces the container to be reloaded in memory</param>
/// <returns>IUnityContainer</returns>
public static IUnityContainer GetContainer(bool forceRefresh = false)
{
if (_container == null || forceRefresh)
{
_container = new UnityContainer();
_container.LoadConfiguration("Default"));
}
return _container;
}
}
}
这引用了web.config中的XML映射,例如:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="ACME.Core" />
<namespace name="ACME.Core.DTO" />
<container name="Default">
<register type="IStatusRepository" mapTo="StatusRepository" />
<register type="INoteRepository" mapTo="NoteRepository" />
</container>
</unity>
错误:
发生System.Configuration.ConfigurationErrorsException HResult = 0x80131902消息=创建时出错 统一的配置节处理程序:无法加载文件或 汇编&#39; Microsoft.Practices.Unity.Configuration&#39;或其中一个 依赖。该系统找不到指定的文件。 Source = Unity.Configuration StackTrace:at Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer container,String containerName)
在 System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host,String typeString,Boolean throwOnError)at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord,FactoryRecord factoryRecord)at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord,FactoryRecord factoryRecord)at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)在 System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(字符串 configKey,布尔&amp; isRootDeclaredHere)
我是否需要以不同方式调用XML配置?
BTW,我只用_container.LoadConfiguration()尝试了它;并收到同样的错误。
答案 0 :(得分:11)
在Github(ENikS)的贡献者的帮助下计算出来。
我正在使用旧的命名空间问题:
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
但是一旦我使用了你提供的新功能,它就会起作用:
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>