2017-02-09 147 views
1

我面临一个奇怪的情况。 我可能对此不甚了解,需要澄清。调用同一实例的两种方法是触发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被调用两次?

+0

你使用什么绑定? 'basicHttpBinding'? – user1429080

+0

是的,这是我正在使用的一个 – ehh

回答

0

在您的使用案例中,您需要使用InstanceContextMode.PerSession服务。这看起来在使用basicHttpBinding时不受支持(例如参见here)。

由于您使用的是basicHttpBinding,因此该服务将使用InstanceContextMode.PerCall。这意味着将为每个到服务的传入呼叫创建一个新的PrintLabelService实例。当然,为label.Print(printerName);调用创建的新实例将不会看到用于label.Generate();调用的实例的本地变量_wordWrapper

为了得到这个工作,你需要切换到使用支持InstanceContextMode.PerSession的不同绑定。 A wsHttpBinding也许?

+0

实际上,它使用basicHttpBinding工作得很好。谢谢 – ehh

+0

它呢?有趣的...无论如何,如果它的工作 - 对你有好处! :-) – user1429080

相关问题