前面几篇文章分别介绍:程序集反射查找,特性,容器,但它们之间贯穿起来,形成查找Attribute注入IOC容器,就得需要下面这个类帮忙:
1.DependencyAttributeRegistrator(依赖特性注入类),有它才能在引擎初始化的时候 查找Attribute 进行注入
public class DependencyAttributeRegistrator {
#region Fieldsprivate readonly ITypeFinder _finder;
private readonly IContainerManger _containerManger;#endregion
#region .ctor
public DependencyAttributeRegistrator(ITypeFinder finder, IContainerManger containerManger)
{
this._finder = finder;
this._containerManger = containerManger;
}
#endregion#region Methods
public virtual IEnumerable<AttributeInfo<DependencyAttribute>> FindServices()
{
foreach (Type type in _finder.FindClassesOfType<object>())
{
var attributes = type.GetCustomAttributes(typeof (DependencyAttribute), false); //这句是关键 查找所有特性
foreach (DependencyAttribute attribute in attributes)
{
yield return new AttributeInfo<DependencyAttribute>
{
Attribute = attribute,
DecorateType = type
};
}
}
}
public virtual void RegisterServices() {
this.RegisterServices(this.FindServices());
}
public virtual void RegisterServices(IEnumerable<AttributeInfo<DependencyAttribute>> services)
{
services = services.OrderBy(it => it.Attribute.Order);
foreach (var info in services)
{
Type serviceType = info.Attribute.ServiceType ?? info.DecorateType;
_containerManger.AddComponent(serviceType,info.DecorateType,info.Attribute.Key,info.Attribute.LiftStyle);
}
}public virtual IEnumerable<AttributeInfo<DependencyAttribute>> FilterServices(
IEnumerable<AttributeInfo<DependencyAttribute>> services, params string[] configurationKeys)
{
return services.Where(s => s.Attribute.Configuration == null || configurationKeys.Contains(s.Attribute.Configuration));
}
#endregion
}
大家可以很清楚看到了吧。其实很简单!