我在C#中使用WCF 4。我正在使用InstanceContextMode设置为单个。实现我的合约的类的实例是使用构造函数创建的,该构造函数接受托管服务的对象的引用。在创建和托管服务主机时传递服务对象。访问承载服务的对象
服务实现代码:
[ServiceBehavior(UseSynchronizationContext = false,
InstanceContextMode = InstanceContextMode.Single)]
public class ServiceImpl : IMyContract
{
private ServiceHoster _sh;
ServiceImpl(ServiceHoster sh)
{
_sh = sh;
}
public string Call(string input)
{
... //Do some processing on the input string
return _sh.ProcessCall(string input);
}
}
ServiceHoster代码:
public class ServiceHoster
{
private ServiceImpl ns;
ServiceHoster()
{
...
Start();
}
private void Start()
{
//Host Service
ns = new ServiceImpl(this);
//Instantiate NetTCP service
_tcpServiceHost = new ServiceHost(ns, new Uri("net.tcp://localhost:8089"));
_tcpServiceHost.Open();
}
private void Stop()
{
if(ns != null && ns.State == CommunicationState.Opened)
ns.Close();
}
public string ProcessCall(string input)
{
...
return result;
}
}
说我现在面临的问题是,我们需要客户端和服务器之间的双向通信。对于双工连接,我们需要设置InstanceContextMode设置为PerSession。
我的问题是:
我可以使用多个值 InstanceContextMode一些如何(我认为这 是不可能的)?
是否有任何其他方法可以让ServiceImpl 对象获得托管它的对象的参考 ?
有什么我可以做的 不同来解决问题?
谢谢。
有没有实现在应用程序中单独服务的特定需求?单身WCF服务很少有很好的用例。如果这是一个问题,这个实现几乎可以杀死服务可伸缩性。 – 2011-05-02 13:54:55
是的,serviceImpl对象需要引用承载该服务的ServiceHoster对象。你能指引我提到你提到的用例吗?谢谢。 – sunilkumarba 2011-05-06 11:00:03
下面的链接提供了有效使用WCF中单例的最佳总结。如果你没有在接受的答案中列出任何东西,你应该使用像wsDualHttpBinding这样的绑定或其他任何支持双工通信的绑定。链接:http://stackoverflow.com/questions/1756487/should-wcf-service-typically-be-singleton-or-not – 2011-05-06 13:19:07