2

When creating an interface proxy using Castle DynamicProxy, it seems that the created proxy object always “inherits” the attributes of the interface.

In general, this is not a real problem, but in my case, I’m using the proxy to generate a WCF service implementation at run-time. The interface has a ServiceContractAttribute, and WCF really does not like it when the implementing type (the service behavior) has that attribute as well.

See the following example:

var generator = new ProxyGenerator();

var interceptor = new ExampleInterceptor();
var proxy = generator.CreateInterfaceProxyWithoutTarget(typeof(ITest), interceptor);

proxy.GetType().CustomAttributes.Select(a => a.AttributeType.Name).Dump();
// SerializableAttribute, XmlIncludeAttribute, ServiceContractAttribute 

typeof(Test).CustomAttributes.Select(a => a.AttributeType.Name).Dump();
// (empty)
public class ExampleInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation) { }
}

[ServiceContract]
public interface ITest { }

public class Test : ITest { }

When looking at the proxy type’s attributes, I get the following three: SerializableAttribute, XmlIncludeAttribute, and ServiceContractAttribute. So not only does DP copy the ServiceContractAttribute, it also adds two more (I don’t really care about those). If I compare that to a manual implementation of my interface, I don’t get any types.

So there is something in DP that actually adds those attributes. Is there any way to influence that attribute generation, to stop DP from adding the interface’s attributes?

poke
  • 369,085
  • 72
  • 557
  • 602

1 Answers1

2

You can use AttributesToAvoidReplicating to avoid specific attributes replication:

AttributesToAvoidReplicating.Add<ServiceContractAttribute>();
haim770
  • 48,394
  • 7
  • 105
  • 133
  • Hah, that’s an unbelivably telling name! I’m not perfectly happy with it being static but since I don’t ever want to replicate a service contract attribute, this works well enough for me. Thanks a lot! Do you happen to know if there’s another fine-grained way to impact this on a per-proxy level? – poke May 08 '17 at 08:55
  • 1
    @poke, You'll have to provide your own `ProxyBuilder` that internally uses its own custom `Generator` that will have to provide a custom `InterfaceProxyWithoutTargetGenerator` implementation. Pretty awkward. – haim770 May 08 '17 at 11:31