将WCF属性应用于服务中的所有方法

Jea*_*erc 10 c# wcf attributes

我有一个自定义属性,我想应用于我的WCF服务中的每个方法.

我这样做:

[MyAttribute]
void MyMethod()
{

}
Run Code Online (Sandbox Code Playgroud)

问题是我的服务包含数百种方法,我不想在所有方法之上编写[Attribute].有没有办法将属性应用于我的服务中的所有方法?

这是我的属性的签名:

//[AttributeUsage(AttributeTargets.Class)]
public class SendReceiveBehaviorAttribute : Attribute, /*IServiceBehavior,*/ IOperationBehavior
Run Code Online (Sandbox Code Playgroud)

在Aliostad回答之后编辑:

我试过这个:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它仍然无效.

Aar*_*ack 9

以下应该通过使用服务行为来添加调用调用者的正确操作行为.

public class MyAttribute : Attribute, IServiceBehavior, IOperationBehavior
{
    #region IServiceBehavior Members
    public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase host)
    {
        foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
        {
            foreach (var operation in endpoint.Contract.Operations)
            {
                operation.Behaviors.Add(this);
            }
        }
    }
    ...
    #endregion

    #region IOperationBehavior Members
    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        dispatchOperation.Invoker = new OperationInvoker(dispatchOperation.Invoker);
    }
    ...
    #endregion
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*tad 6

根据IServiceBehaviour文档,如果您实现此接口并创建属性并将其放在类级别,它将应用于所有操作:

创建一个实现IServiceBehavior的自定义属性,并使用它来标记要修改的服务类.构造ServiceHost对象时,使用反射来发现服务类型上的属性.如果任何属性实现IServiceBehavior,则会将它们添加到ServiceDescription上的behavior集合中.


UPDATE

而不是实现IOperationBehaviour,IServiceBehaviour通过循环遍历所有操作添加所需的行为:

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 
    }                        
}
Run Code Online (Sandbox Code Playgroud)