我有一个由 Windows 服务托管的 WCF 服务。当客户端连接到 WCF 服务时,我不知道如何通知 Windows 服务。基本上我在 Windows 服务中启动 WCF 服务的所有内容都是这样的:
private ServiceHost sHost;
WCF.WCFService wcfService = new WCF.WCFService();
sHost = new ServiceHost(wcfService);
sHost.Open();
我可以使用 wcfService 对象通过 Windows 服务调用 WCF 服务中的方法。有没有什么方法可以在客户端连接到 WCF 服务时触发某种事件?
最佳答案
该服务作为根据 ServiceBehaviourAttribute
属性实例化的对象运行 InstanceContextMode
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
// ...
InstanceContextMode 的值为
单个
- 为所有 session 和调用运行的单个服务实例PerSession
- 为每个 session (即每个客户端)运行的服务实例PerCall
- 为每次调用实例化服务实例,即使来自单个客户端也是如此
默认值为PerSession
,这对大多数场景都有意义。假设您正在使用 PerSession
,您可以将任何您喜欢的“连接逻辑”放入服务的构造函数中。
// you don't need to specify PerSession as it is default, but I have for clarity
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
public MyService()
{
// constructor will be called for each new client session
// eg fire an Event, log a new client has connected, etc
}
// ...
}
您需要小心地在构造函数中运行代码,因为在构造函数完成之前服务将不可用。如果您想做任何可能需要时间的事情,请触发一个事件或发送一个线程来执行该工作。
关于c# - 如何在客户端连接时通知 WCF 服务的主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7509005/