我有以下自定义属性;它是标记需要显式注册的接口,而不是依赖于Castle Windsor的惯例注册:
using System;
[AttributeUsage(
AttributeTargets.Interface | AttributeTargets.Class,
Inherited = true)]
public class ExplicitDependencyRegistrationRequiredAttribute : Attribute
{
}
然后将其应用于界面,如下所示:
using Dependencies.Attributes;
[ExplicitDependencyRegistrationRequired]
public interface IRandomNumberGenerator
{
int GetRandomNumber(int max);
}
下面有一个简单的具体实现:
using System;
public class RandomNumberGenerator : IRandomNumberGenerator
{
private readonly Random random = new Random();
public int GetRandomNumber(int max)
{
return random.Next(max);
}
}
这个想法是,当按照惯例在Castle Windsor注册组件时,我们不必担心重复注册或添加异常;相反,我们只需要确保界面标有此属性。然后过滤它的代码如下:
Type exclusionType = typeof(ExplicitDependencyRegistrationRequiredAttribute);
BasedOnDescriptor selectedTypes =
Classes
.FromAssembly(assembly)
.Where(t => !Attribute.IsDefined(t, exclusionType, true))
.WithServiceAllInterfaces();
问题是Attribute.IsDefined
过滤器似乎不起作用,从具有该属性的接口继承的组件仍在注册。
当我明确地将属性添加到RandomNumberGenerator
类时,过滤器可以正常工作;但是它似乎没有从接口继承或 Castle Windsor没有正确地获取自定义属性。
任何帮助将不胜感激