【问题标题】:Calling two methods of the same instance is triggering the Dispose method in WCF调用同一实例的两个方法正在触发 WCF 中的 Dispose 方法
【发布时间】: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


【解决方案1】:

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

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

为了让它工作,您需要切换到使用支持InstanceContextMode.PerSession 的不同绑定。 wsHttpBinding 可能吗?

【讨论】:

  • 实际上它与 basicHttpBinding 配合得很好。谢谢
  • 有吗?有趣......无论如何,如果它有效 - 对你有好处! :-)
猜你喜欢
  • 2014-10-12
  • 2012-05-21
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 2013-04-01
  • 1970-01-01
相关资源
最近更新 更多