按惯例注册组件时,CustomAttribute未正确过滤

时间:2012-12-28 15:11:24

标签: c# dependency-injection attributes castle-windsor conventions

我有以下自定义属性;它是标记需要显式注册的接口,而不是依赖于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没有正确地获取自定义属性。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

实现接口的类在接口are not inherited上的属性。您需要在类上声明属性(再次),以使其按您希望的方式工作。