我有一个 unity 配置文件(App.config
),如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IProductService" type="UnityExample.Service.IProductService, UnityExample.Service" />
<containers>
<container name="Service">
<register type="IProductService" mapTo="ProductService"/>
</container>
</containers>
</unity>
</configuration>
现在,我要从file
上方加载配置。
var container = new UnityContainer().LoadConfiguration("Service");
但是我收到以下错误:
[ArgumentNullException:值不能为null。参数名称:section] Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer 容器,UnityConfigurationSection部分,字符串containerName)
答案 0 :(得分:3)
我能够使它工作。我已经使用与您使用的相同的名称空间创建了一个演示控制台应用程序,如下所示:
已安装Nuget软件包:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Unity" version="5.8.6" targetFramework="net461" />
<package id="Unity.Abstractions" version="3.3.0" targetFramework="net461" />
<package id="Unity.Configuration" version="5.2.3" targetFramework="net461" />
</packages>
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="UnityExample" />
<namespace name="UnityExample.Service" />
<containers>
<container name="Service">
<register type="IProductService" mapTo="ProductService"/>
</container>
</containers>
</unity>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Unity.Configuration" publicKeyToken="6d32ff45e0ccc69f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
代码:
namespace UnityExample.Service
{
public interface IProductService
{
}
public class ProductService : IProductService
{
}
}
主要:
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Unity;
using UnityExample.Service;
namespace UnityExample
{
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container, "Service");
IProductService service = container.Resolve<IProductService>();
}
}
}