0

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/...)?

  • What does `instance.GetType().FullName` say? – Lasse V. Karlsen Dec 06 '16 at 10:57
  • @LasseV.Karlsen `Castle.Proxies.**BaseType**Proxy`, `propertyInfo` is not null, thus the mixin is applied according to the `proxyGenerationOptions`. –  Dec 06 '16 at 11:01
  • I'm guessing you do not want the attribute on `IMixin` interface? – Krzysztof Kozmic Dec 25 '16 at 12:04
  • @KrzysztofKozmic not necessarily - but if that's a viable option, why not :) the next question that comes to my mind: why would it work on interfaces, but not on concrete classes? –  Dec 25 '16 at 14:52
  • The way mixins were built for DynamicProxy is they work just like additional `target`s on interface proxies, so they do not expose any details of the implementing mixin target class. – Krzysztof Kozmic Dec 26 '16 at 01:01

1 Answers1

0

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.