Tôi muốn có loại bạn muốn khởi tạo cho một giá trị cụ thể trong tệp cấu hình. Cái gì như:
<TypeMappings>
< tên TypeMapping = "cuộc sống" type = "Entities.LifeEntity, Tổ chức"/>
< TypeMapping name = "sở hữu" type = "Entities.PropertyEntity, Tổ chức"/>
< tên TypeMapping = "khuyết tật" type = "Entities.DisabilityEntity, Tổ chức"/>
< TypeMapping name = "creditcard" type = "Entities.CreditCardEntity, Tổ chức"/>
</TypeMappings >
Bên trong phương pháp của bạn, bạn sau đó có thể trích xuất tất cả các đăng ký từ các tập tin cấu hình, tìm ra phù hợp với phản ánh một và sử dụng để nhanh chóng các loại, nếu đăng ký là không tìm thấy, bạn ném một ngoại lệ.
Dưới đây là một số mẫu mã:
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);
}
}
Rất nhiều các khuôn khổ DI phép bạn cung cấp nhiều đăng ký cho một giao diện mà bạn có thể truy vấn dựa trên siêu dữ liệu. Khám phá this link về cách MEF thực hiện xuất bằng siêu dữ liệu.
Nguồn
2009-07-29 01:55:44
Đây là cách tôi thường tiếp cận một nhà máy, đặc biệt là trong các thư viện nơi ứng dụng của khách hàng có thể muốn thêm triển khai của riêng họ. – Joon
Nguồn đó để biết thêm liên kết thông tin không còn khả dụng, cơ hội nào đó được lưu trữ ở một nơi khác? Hoặc là có một bài tương đương ở đâu đó? –
@Sam Heuck Tôi đã liên kết một phiên bản đã lưu trữ – Lennart