我寧願讓你想要在配置文件中爲特定值實例化的類型。 是這樣的:
<TypeMappings>
< 名稱TypeMapping = 「生命」 類型= 「Entities.LifeEntity,實體」/ >
< 名稱TypeMapping = 「屬性」 類型= 「Entities.PropertyEntity,實體」/ >
< 名稱TypeMapping = 「殘疾」 類型= 「Entities.DisabilityEntity,實體」/ >
< 名稱TypeMapping = 「的信用卡」 類型= 「Entities.CreditCardEntity,實體」/ >
</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框架,讓你提供,你可以查詢基於元數據的接口多個註冊。 查看this link瞭解MEF如何使用元數據進行導出。
這是我通常接近工廠的方式,特別是在客戶端應用程序可能希望添加自己的實現的庫中。 – Joon 2009-07-31 07:45:47
更多信息鏈接的源代碼不再可用,它被託管在其他地方的任何機會?或者在某個地方是否有相應的帖子? – 2015-05-18 14:39:51
@Sam Heuck我鏈接了一個存檔版本 – Lennart 2017-02-10 09:34:48