InstanceContextMode.PerCall在wcf中充当InstanceContextMode.Single

时间:2014-01-18 14:01:04

标签: c# .net wcf

我试图仅在代码的帮助下创建一个wcf服务主机(不涉及配置)。 我为wcftestservice设置了一个静态int和InstanceContextMode.PerCall。根据互联网上提供的tutorial,我对wcf的每次调用应该具有相同的值吗?

注意:我在控制台应用程序以及Windows服务中测试了这种行为,我在wcf测试客户端的帮助下测试了这种行为

以下是代码:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class WcfServiceTest : IContract
{
    static int _counter;
    public string GetData(string p1)
    {
        return Convert.ToString(_counter++);
    }
}

合同:

[ServiceContract]
public interface IContract
{
    [OperationContract]
    string GetData(string p1);
}

服务主机代码:

    static ServiceHost _servicehost;

    static void Main(string[] args)
    {
        string tcpPort = "8081";
        string httpPort = "8888";
        string urlWithoutProtocol = "{0}://localhost:{1}/WcfServiceTest";
        string netTcpAddress = string.Format(urlWithoutProtocol, "net.tcp", tcpPort);
        string httpAddress = string.Format(urlWithoutProtocol, "http", httpPort);

        string netTcpMexAddress = netTcpAddress + "/mex";
        string httpMexAddress = httpAddress + "/mex";
        if (_servicehost != null)
        {
            _servicehost.Close();
        }
        _servicehost = new ServiceHost(typeof(wcftest.WcfServiceTest));
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        //smb.HttpGetUrl = httpUri;
        //smb.HttpGetEnabled = true;
        _servicehost.Description.Behaviors.Add(smb);
        _servicehost.AddServiceEndpoint(typeof(wcftestcontract.IContract), new NetTcpBinding(), netTcpAddress);
        Binding mexTcpBinding = MetadataExchangeBindings.CreateMexTcpBinding();
        _servicehost.AddServiceEndpoint(typeof(IMetadataExchange), mexTcpBinding, netTcpMexAddress);

        _servicehost.AddServiceEndpoint(typeof(wcftestcontract.IContract), new BasicHttpBinding(), httpAddress);
        Binding mexHttpBinding = MetadataExchangeBindings.CreateMexHttpBinding();
        _servicehost.AddServiceEndpoint(typeof(IMetadataExchange), mexHttpBinding, httpMexAddress);

        _servicehost.Open();
        Console.ReadKey();
    }

1 个答案:

答案 0 :(得分:1)

如果要检查它是否仅为Singleton模式创建一次,并且每次都为PerCall模式创建,那么您需要在构造函数中增加变量:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class WcfServiceTest : IContract
{
    static int _counter;

    public WcfServiceTest()
    {
        _counter++;
    }
    public string GetData(string p1)
    {
        return Convert.ToString(_counter);
    }
}

然后,对于PerCall,每个电话号码都会增加,而对于Singleton模式,它不会增加

是的,教程有一个错误。在他们的样本中应该没有静态修饰符:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class MyService:IMyService
{
    int m_Counter = 0;

    public int MyMethod()
    {
        m_Counter++;
        return m_Counter;
    }       
}

静态变量意味着它对于所有对象实例应该是相同的。因此,对于静态变量,PerCall和Signleton模式之间没有区别,因为它们是相同的。

相关问题