2017-02-09 142 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

相關問題