【发布时间】:2017-02-09 13:11:19
【问题描述】:
我正面临一个奇怪的情况。 我可能对此了解较少,需要澄清一下。
我使用 WCF 做一些打印工作。 以下是提出我的问题的尽可能小的代码 sn-p。
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);
}
}
调用时(单元测试部分)
label.Generate();
然后
label.Print(printerName);
服务中的 dispose 方法被调用了两次(对于上述每个调用)。然后 _wordWrapper 被重新初始化,这会破坏它的状态。
为什么每次调用都会调用 dispose,如何防止 Dispose 被调用两次?
【问题讨论】:
-
你使用什么绑定?
basicHttpBinding? -
是的,我正在使用这个
标签: c# web-services wcf c#-4.0