【问题标题】:Programmatically adding BehaviorExtensionElement以编程方式添加 BehaviorExtensionElement
【发布时间】:2018-01-15 08:34:50
【问题描述】:

我有一个ServiceHost,我正在以编程方式创建,我想在其中添加一个Behaviour。我可以使用host.Description.Behaviors.Add() 添加行为,但我找不到添加BehaviorExtensionElement 部分的方法。有一个 host.Extensions 集合,但它接受 ServiceHostBase。基本上我想把这个 web.config 部分翻译成代码:

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceDebug includeExceptionDetailInFaults="false" />
          <errorHandler />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="errorHandler" type="MyService.ErrorHandlerBehaviorExtensionElement, MyService" />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>

【问题讨论】:

    标签: c# .net wcf .net-4.5


    【解决方案1】:

    服务行为

    实现 IServiceBehavior 的服务行为是修改整个服务运行时的主要机制。可以通过三种机制向服务添加服务行为。

    1. 使用服务类的属性。构造 ServiceHost 时,ServiceHost 实现使用反射来发现服务类型的属性集。如果这些属性中的任何一个是 IServiceBehavior 的实现,它们将被添加到 ServiceDescription 上的行为集合中。这允许这些行为参与服务运行时的构建。

    2. 以编程方式将行为添加到 ServiceDescription 上的行为集合中。这可以通过以下代码行来完成:

      ServiceHost host = new ServiceHost(/* 参数/);
      host.Description.Behaviors.Add(/
      服务行为 */);

    3. 实现扩展配置的自定义 BehaviorExtensionElement。这样就可以使用应用程序配置文件中的服务行为。

    所以我认为不需要同时添加 Behaviors 和 BehaviorExtensionElement。 还要检查:https://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 2021-08-23
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多