借用MEF对WCF实现扩展

本文介绍了一种利用Managed Extensibility Framework (MEF)来简化Windows Communication Foundation (WCF)扩展的方法。通过继承相关接口并使用特定工具,开发者可以轻松实现WCF服务的行为扩展而无需复杂的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MEFing WCF Extensibility

You can download the code here

Wouldn’t it be nice to extend WCF just by inheriting the relevant interface (IServiceBehavior, IDispatchMessageInspector, ext…) and having it hooked without wasting your time on finding the right way of hooking it?

Well this post is all about this topic.

How does it work?

I wrote 2 helper project MEFContracts and WcfPrimitivePlugins which responsible for that magic, and you will also need reference to MEF.

For any of your WCF services or client proxy, you have to add reference to the MEFContracts project and ComponentModel project (which is the MEF CTP 6 implementation), then place the WcfPrimitivePlugins.dll under relative folder called “Plug-Ins” (you can change this place by adding MEF catalog using ).

Modify your client proxy to inherit from MefWcfProxy<TChannel> instead of ClientBase<TChannel>.

On the service side you have 2 option:

1) using MefHost for hosting your service.

2) decorate your service with [MefBehavior] attribute

Writing your WCF extensibility

Writing WCF extensibility is made simple.

Just create class library application and implement the WCF extensibility interface

  • IServiceBehavior 
  • IEndpointBehavior
  • IOperationBehavior
  • IParameterInspector
  • IOperationInvoker
  • IInstanceContextInitializer
  • IDispatchMessageInspector
  • IClientMessageInspector
  • IErrorHandler

optional: add reference to MEFContracts for having advance hooking for timeout, Throttling, and more

Running the sample

The solution can be compile with different compiler switches for demonstrating different scenarios:

image

  • ByAttribute (will hook the service using [MefBehavior] attribute)
  • Debug (will hook the service using MefHost)
  • IgnoreInterception (will detach the hooking)
  • LimitedThrottling (will cause exceptions by limiting the concurrent session and reduce the timeout – that how you see the IErrorHandler plug-in in action)

So choose the compiler switch (recommended: delete the bin folder), compile the solution and run  (WcfClientConsole and WcfHostConsole projects are configure the start with F5)

Summary

Writing WCF extension should be focus on extension and the hooking should be transparent.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值