Search code examples
.netreflectionmixinscustom-attributescastle-dynamicproxy

How can I mixin attributes with Dynamic Proxy defined on mixin instances?


I have following mixin defined:

public interface IMixin
{
  string SomeProperty { get; set; }
}

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

This gets injected with the following "proxy generating"-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 */);

The problem I am facing:

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

attribute is null.

How can I mixin a concrete instance, including the attributes defined in the type (on properties/class/methods/fields/...)?


Solution

  • There's a workaround available:

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

    The only disadvantage: You can't define any attributes on members of the type, just on the class itself.