将消息发送到WCF宿主进程
我有一个托管WCF服务的控制台应用程序。我希望能够从WCF服务的方法触发一个事件,并在WCF服务的宿主进程处理该事件。这可能吗?我会怎么做呢?我可以从ServiceHost的派生自定义类?
I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?
您不需要从的ServiceHost 。还有其他的方法来你的问题。
You don't need to inherit from ServiceHost
. There are other approaches to your problem.
您可以传递的,而不是一个类型的ServiceHost $ C $服务类的一个实例, C>。因此,您可以创建实例,然后再开始的
的ServiceHost
,并添加自己的事件处理程序,它暴露了任何事件。
You can pass an instance of the service class, instead of a type to ServiceHost
. Thus, you can create the instance before you start the ServiceHost
, and add your own event handlers to any events it exposes.
下面是一些示例代码:
MyService svc = new MyService();
svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();
有使用这种方法的时候一些注意事项,如在的 http://msdn.microsoft.com/en-us/library/ms585487.aspx
There are some caveats when using this approach, as described in http://msdn.microsoft.com/en-us/library/ms585487.aspx
或者你可以有一个众所周知的单例类,你的服务实例了解并明确调用它的方法时,事件发生了。
Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.