我宁愿拥有您想要为配置文件中的特定值实例化的类型。就像是:
<TypeMappings>
<TypeMapping name = "life" type="Entities.LifeEntity,Entities"/>
<TypeMapping name = "property" type="Entities.PropertyEntity,Entities"/>
<TypeMapping name = "disability" type="Entities .DisabilityEntity,Entities"/>
<TypeMapping name = "creditcard" type ="Entities.CreditCardEntity,Entities"/>
</TypeMappings >
在您的方法中,您可以从配置文件中提取所有注册,找到匹配的注册并使用反射来实例化类型,如果未找到注册,则抛出异常。
这是一些示例代码:
namespace Entities
{
public interface IResultEntity
{
}
public class LifeEntity : IResultEntity
{
public override string ToString()
{
return("I'm a Life entity");
}
}
public class PropertyEntity : IResultEntity
{
public override string ToString()
{
return("I'm a Property Entity");
}
}
public class CreditCardEntity : IResultEntity
{
public override string ToString()
{
return("I'm a CreditCard Entity ");
}
}
public class DisabilityEntity : IResultEntity
{
public override string ToString()
{
return("I'm a Disability Entity");
}
}
}
public static Entities.IResultEntity GetEntity(string entityTypeName,string fileName)
{
XDocument doc = XDocument.Load(fileName);
XElement element = doc.Element("TypeMappings").Elements("TypeMapping")
.SingleOrDefault(x => x.Attribute("name").Value == entityTypeName);
if(element == null)
{
throw new InvalidOperationException("No type mapping found for " + entityTypeName);
}
string typeName = element.Attribute("type").Value;
Type type = Type.GetType(typeName);
Entities.IResultEntity resultEntity = Activator.CreateInstance(type) as Entities.IResultEntity;
if(resultEntity == null)
{
throw new InvalidOperationException("type mapping for " + entityTypeName + " is invalid");
}
return resultEntity;
}
public static void Main()
{
try
{
Entities.IResultEntity result = GetEntity("life", @"c:\temp\entities.xml");
Console.WriteLine(result);
result = GetEntity("property", @"c:\temp\entities.xml");
Console.WriteLine(result);
result = GetEntity("disability", @"c:\temp\entities.xml");
Console.WriteLine(result);
result = GetEntity("creditcard", @"c:\temp\entities.xml");
Console.WriteLine(result);
result = GetEntity("foo", @"c:\temp\entities.xml");
Console.WriteLine(result);
}
}
许多 DI 框架允许您为可以基于元数据查询的接口提供多个注册。查看此链接,了解 MEF 如何使用元数据进行导出。