首页 / 软件开发 / .NET编程技术 / Castle IOC容器实践之TypedFactory Facility(二)
Castle IOC容器实践之TypedFactory Facility(二)2011-01-31 cnblogs terrylee主要内容TypedFactory Facility原理分析……在TypedFactory Facility中,有一个FactoryEntry类,这个类与我们平时项目开发中的实体类有一些类似,它用来记录工厂的相关信息,包括工厂的ID,工厂的接口,创建方法和销毁方法。这个类实现如下:public class FactoryEntry
{
private String _id;
private Type _factoryInterface;
private String _creationMethod;
private String _destructionMethod;
public FactoryEntry(String id, Type factoryInterface, String creationMethod, String destructionMethod)
{
// 省略了验证及异常处理
_id = id;
_factoryInterface = factoryInterface;
_creationMethod = creationMethod;
_destructionMethod = destructionMethod;
}
public String Id
{
get { return _id; }
}
public Type FactoryInterface
{
get { return _factoryInterface; }
}
public String CreationMethod
{
get { return _creationMethod; }
}
public String DestructionMethod
{
get { return _destructionMethod; }
}
}
TypedFactoryFacility同样是继承于AbstractFacility,关于Facility的继承关系我在前面的文章中已经说过了。TypedFactory Facility在初始化的时候首先会获取工厂的类型,通过SubSystem来得到:protected override void Init()
{
Kernel.AddComponent( "typed.fac.interceptor", typeof(FactoryInterceptor) );
ITypeConverter converter = (ITypeConverter)
Kernel.GetSubSystem( SubSystemConstants.ConversionManagerKey );
AddFactories(FacilityConfig, converter);
}
protected virtual void AddFactories(IConfiguration facilityConfig, ITypeConverter converter)
{
if (facilityConfig != null)
{
foreach(IConfiguration config in facilityConfig.Children["factories"].Children)
{
String id = config.Attributes["id"];
String creation = config.Attributes["creation"];
String destruction = config.Attributes["destruction"];
Type factoryType = (Type)
converter.PerformConversion( config.Attributes["interface"], typeof(Type) );
try
{
AddTypedFactoryEntry(
new FactoryEntry(id, factoryType, creation, destruction) );
}
catch(Exception ex)
{
throw new ConfigurationException("Invalid factory entry in configuration", ex);
}
}
}
}