Castle动态代理不会将自定义属性写入代理

时间:2012-06-24 16:07:24

标签: c# castle-dynamicproxy

我有简单的单元测试来重现情况:

[Test]
public void Castle_Writes_Attribute_To_Proxy()
{
    var generator = new ProxyGenerator();
    var proxy = generator.CreateClassProxy<MyType>();

    var type = proxy.GetType();

    var prop = type.GetProperty("SomeProp");

    var attrs = prop.GetCustomAttributes(typeof(DescriptionAttribute), true);

    Assert.That(attrs.Length, Is.Not.EqualTo(0));
}

public class MyType
{
    [Description("some description here")]
    public virtual string SomeProp { get; set; }
}

测试失败,因为Castle动态代理不会写自定义属性,

可以将父属性写入生成的代理吗?

解: 使用Attribute.GetCustomAttributes(...)

var attrs = Attribute.GetCustomAttributes(prop, typeof(DescriptionAttribute));

1 个答案:

答案 0 :(得分:3)

改为使用Attribute.GetCustomAttributes(...)the method you're using doesn't work on properties