加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:40:12 所属栏目:百科 来源:网络整理
导读:我有一个自定义属性,我想要应用于我的WCF服务中的每个方法. 我这样做: [MyAttribute]void MyMethod(){} 问题是我的服务包含数百种方法,我不想在其中写出[Attribute].有没有办法在我的服务中将属性应用于我所有的方法? 这是我的属性的签名: //[AttributeUs
我有一个自定义属性,我想要应用于我的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 
    }                        
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读