我已經創建了IDispatchMessageInspector接口的自定義實現,並且我的代碼工作得很好。WCF服務主機何時銷燬自定義IDispatchMessageInspector?
我的問題是,當WCF服務主機被終止和/或釋放我的類的一個實例時,我需要釋放一些託管對象。我的對象免費實現IDisposable,但它們不會被丟棄。我已經通過MSDN庫(更困惑)和SO歸檔,但沒有發現任何解決「WCF服務主機銷燬MessageInspectors的時間/地點?」問題的任何內容。
我需要在某處掛鉤事件嗎?我是否需要從ServiceModel名稱空間實現更加神祕的東西?
任何人都可以給我一個正確的方向指針嗎?
編輯1:澄清
目前,我在IDE中使用自動運行的網絡服務器。我不是最終在生產中控制主機,可以是任何有效的服務器主機選擇。
MyCore.My和MyCore.MyProperties對象是我試圖在WCF服務器主機被終止/退回時處理的對象。
即使我殺死了web服務器進程(任務欄中的那些東西),Dispose()也不會被調用。
編輯2:添加了代碼片段。
using /* snip */
using MyCore = Acme.My;
namespace My.SOAP
{
public class MyMessageInspector : IDispatchMessageInspector
{
protected static MyCore.My _My;
protected static MyCore.MyProperties _MyProps;
protected static ConcurrentDictionary<string, MyCore.AnotherSecretThing> _anotherSecretThings = new ConcurrentDictionary<string, MyCore.AnotherSecretThing>();
protected static void InitMy()
{
if (_My != null) return;
_MyProps = new MyCore.MyProperties();
MyCore.MySqlDatabaseLogger logger = new MyCore.MySqlDatabaseLogger(_MyProps);
_My = new MyCore.My(logger);
}
public MyMessageInspector()
{
InitMy();
}
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
MyMessageHeader header = null;
try
{
// find My header
Int32 headerPosition = request.Headers.FindHeader(MyMessageHeaderKey.MyHeaderElementName, MyMessageHeaderKey.MyNamespace);
// get reader
XmlDictionaryReader reader = request.Headers.GetReaderAtHeader(headerPosition);
// get My header object
header = MyMessageHeader.ReadHeader(reader);
// add to incoming messages properties dictionary
OperationContext.Current.IncomingMessageProperties.Add(MyMessageHeaderKey.MyHeaderElementName, header);
}
catch (Exception ex)
{
// log via ExceptionHandlingBlock
}
MyCore.SecretThings SecretThings = CreateSecretThings(/* snip */);
return SecretThings.Id;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
MyCore.SecretThings req = _My.GetSecretThingsOnThread();
// if we didn't find the SecretThings, there is nothing to stop() and no data to put in the MessageHeaders
if (req == null) return;
MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
reply = buffer.CreateMessage();
var MyHeader = new MyMessageHeader(/* snip */);
reply.Headers.Add(MyHeader);
req.Stop(MyCore.Status.SUCCESS);
}
protected MyCore.SecretThings CreateSecretThings(string key, Dictionary<string, string> ids)
{
/* snip */
return _My.GetSecretThings(/* snip */);
}
}
}
可我們看到的例子嗎?你想要在你的DispatchMessageInspector中處理你的對象嗎? – Mike 2012-07-17 20:24:05