我面臨一個奇怪的情況。 我可能對此不甚瞭解,需要澄清。調用同一實例的兩種方法是觸發WCF中的Dispose方法
我在做一些使用WCF的打印材料。 以下是儘可能最小的代碼片段來陳述我的問題。
WCF服務
[ServiceContract]
public interface IPrintLabelService
{
[OperationContract]
bool Generate(string templateFullFilename, Dictionary<string, string> textFields, Dictionary<string, string> imageFields);
[OperationContract]
bool Print(string printerName);
}
public class PrintLabelService : IPrintLabelService, IDisposable
{
private WordWrapper _wordWrapper;
public PrintLabelService()
{
_wordWrapper = new WordWrapper();
}
public bool Generate(string templateFullFilename, Dictionary<string, string> textFields, Dictionary<string, string> imageFields)
{
return _wordWrapper.Generate(textFields, imageFields);
}
public bool Print(string printerName)
{
return _wordWrapper.PrintDocument(printerName);
}
public void Dispose()
{
if (_wordWrapper != null)
{
_wordWrapper.Dispose();
}
}
}
單元測試
public void PrintLabelTestMethod()
{
ILabel label = null;
try
{
//some stuff
// ...
// Act
label.Generate();
label.Print(printerName);
}
finally
{
label.Dispose();
}
}
標籤類
class Label : ILabel
{
private readonly PrintLabelServiceClient _service;
private bool _disposed = false;
public Label(string templateFullFileName)
{
_service = new PrintLabelServiceClient();
}
public bool Generate()
{
return _service.Generate(TemplateFullFileName, textFields, imageFields);
}
public bool Print(string printerName)
{
return _service.Print(printer.Name);
}
}
當CAL靈(單位測試部分)
label.Generate();
然後
label.Print(printerName);
在服務dispose方法被調用兩次(用於上述呼叫中的每一個)。然後_wordWrapper正在重新初始化,正在破壞其狀態。
爲什麼每次調用都會調用dispose,並且如何防止Dispose被調用兩次?
你使用什麼綁定? 'basicHttpBinding'? – user1429080
是的,這是我正在使用的一個 – ehh