如何将属性属性与在混合蛋白实例上定义的动态代理混合



我已定义以下mixin:

public interface IMixin
{
  string SomeProperty { get; set; }
}
public class Mixin : IMixin
{
  [SomeAttribute]
  public string SomeProperty { get; set; }
}

这将注入以下"代理生成" -Call:

using Castle.DynamicProxy;
var proxyGenerationOptions = new ProxyGenerationOptions();
var mixin = new Mixin();
proxyGenerationsOptions.AddMixinInstance(mixin);
var additionalInterfacesToProxy = new []
                                  {
                                    typeof (IMixin)
                                  };
var proxyGenerator = new ProxyGenerator();
var proxy = proxyGenerator.CreateClassProxy(/* base type */,
                                            additionalInterfacesToProxy,
                                            proxyGenerationOptions,
                                            /* interceptor instance */);

我面临的问题:

var instance = /* proxy instance */;
var propertyInfo = instance.GetType()
                           .GetProperty(nameof(IMixin.SomeProperty));
var attribute = Attribute.GetCustomAttribute(propertyInfo,
                                             typeof(SomeAttribute),
                                             true);

attribute为null。

我如何混合一个具体实例,包括类型中定义的属性(on properties/class/class/methods/fields/...:

有一个解决方法:

using System.Reflection.Emit;
using Castle.DynamicProxy;
var proxyGenerationOptions = new ProxyGenerationsOptions();
/* ... */
var customAttributeBuilder = new CustomAttributeBuilder(/* ... */);
proxyGenerationOptions.AdditionalAttributes.Add(customAttributeBuilder);

唯一的缺点:您不能在类型成员上定义任何属性,仅在类本身上。

最新更新