以编程方式添加BehaviorExtensionElement

时间:2018-01-15 08:34:51

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

我有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>

1 个答案:

答案 0 :(得分:1)

服务行为

实现IServiceBehavior的服务行为是修改整个服务运行时的主要机制。将服务行为添加到服务有三种机制。

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

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

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

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

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

相关问题