Unity 支持XML 配置(AKA 设计时配置)和编程配置(AKA 运行时配置)。XML 配置必须遵循Unity 配置架构。
开箱即用的 XML 配置与 .NET 配置挂钩,因此如果不想使用 app.config/web.config 并手动加载,我认为您必须创建自己的 ConfigurationSection 类来加载配置信息:
public class MyUnityConfigurationSection : UnityConfigurationSection
{
public string Serialize()
{
return SerializeSection(null, UnityConfigurationSection.SectionName,
ConfigurationSaveMode.Full);
}
public void LoadConfigurationFile(string fileName)
{
Deserialize(File.ReadAllText(fileName));
}
public void Deserialize(string xml)
{
using (var sr = new StringReader(xml))
using (var reader = XmlTextReader.Create(sr))
{
base.DeserializeSection(reader);
}
}
}
然后您可以从字符串或文件加载配置:
string configString = "<unity xmlns=\"http://schemas.microsoft.com/practices/2010/unity\">\r\n <container>\r\n <register type=\"IEmployee\" mapTo=\"FakeEmployee\" />\r\n </container>\r\n</unity>";
var config = new MyUnityConfigurationSection();
config.Deserialize(configString);
IUnityContainer container = new UnityContainer();
container.LoadConfiguration(config);
您可能希望在配置程序集中创建一个方法:
public void Configure(IUnityContainer container)
{
// internally configure the container via XML or programmatically
}