我有一个自定义属性,我想要应用于我的WCF服务中的每个方法.
我这样做:
[MyAttribute] void MyMethod() { }
问题是我的服务包含数百种方法,我不想在其中写出[Attribute].有没有办法在我的服务中将属性应用于我所有的方法?
这是我的属性的签名:
//[AttributeUsage(AttributeTargets.Class)] public class SendReceiveBehaviorAttribute : Attribute,/*IServiceBehavior,*/ IOperationBehavior
阿利奥斯塔德答复后的编辑:
我试过这个:
public void ApplyDispatchBehavior(ServiceDescription desc,ServiceHostBase host) { foreach (ChannelDispatcher cDispatcher in host.ChannelDispatchers) { foreach (EndpointDispatcher eDispatcher in cDispatcher.Endpoints) { foreach (DispatchOperation op in eDispatcher.DispatchRuntime.Operations) { op.Invoker = new OperationInvoker(op.Invoker); } } } }
然后:
public void AddBindingParameters(ServiceDescription serviceDescription,ServiceHostBase serviceHostBase,Collection<ServiceEndpoint> endpoints,BindingParameterCollection bindingParameters) { foreach (ChannelDispatcher cDispatcher in serviceHostBase.ChannelDispatchers) { foreach (EndpointDispatcher eDispatcher in cDispatcher.Endpoints) { foreach (DispatchOperation op in eDispatcher.DispatchRuntime.Operations) { op.Invoker = new OperationInvoker(op.Invoker); } } } }
但它仍然不行.
解决方法
根据
IServiceBehaviour文档,如果您实现此界面并创建一个属性并将其放在类级别,它将被应用于所有操作:
Create a custom attribute that
implements IServiceBehavior and use it
to mark service classes that are to be
modified. When a ServiceHost object is
constructed,uses reflection to
discover the attributes on the service
type. If any attributes implement
IServiceBehavior,they are added to
the behaviors collection on
ServiceDescription.
UPDATE
通过循环执行所有操作,可以在IServiceBehavIoUr中添加必需的行为,而不是实现IOperationBehavIoUr:
foreach (EndpointDispatcher epDisp in chDisp.Endpoints) { epDisp.DispatchRuntime.MessageInspectors.Add(this); foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations) { op.ParameterInspectors.Add(this); // JUST AS AN EXAMPLE } }