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?

1 Answer 1

2

You can use AttributesToAvoidReplicating to avoid specific attributes replication:

AttributesToAvoidReplicating.Add<ServiceContractAttribute>();
Sign up to request clarification or add additional context in comments.

2 Comments

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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.