Search code examples
c#castle-dynamicproxy

Interface proxy without inheriting attributes


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?


Solution

  • You can use AttributesToAvoidReplicating to avoid specific attributes replication:

    AttributesToAvoidReplicating.Add<ServiceContractAttribute>();