向WCF主机进程发送消息
时间:2020-03-06 14:47:11 来源:igfitidea点击:
我有一个托管WCF服务的控制台应用程序。我希望能够从WCF服务中的方法触发事件,并在WCF服务的托管过程中处理该事件。这可能吗?我该怎么做?我可以从ServiceHost派生自定义类吗?
解决方案
我们无需从ServiceHost
继承。还有其他方法可以解决问题。
我们可以将服务类的实例(而不是类型)传递给ServiceHost
。因此,我们可以在启动ServiceHost
之前创建实例,并将我们自己的事件处理程序添加到它公开的任何事件中。
这里是一些示例代码:
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中所述,使用此方法时有一些注意事项
或者,我们可以有一个众所周知的单例类,服务实例知道该类,并在事件发生时显式调用其方法。
using ... using ... namespace MyWCFNamespace { class Program { static void Main(string[] args){ //instantiate the event receiver Consumer c = new Consumer(); // instantiate the event source WCFService svc = new WCFService(); svc.WCFEvent += new SomeEventHandler(c.ProcessTheRaisedEvent); using(ServiceHost host = new ServiceHost(svc)) { host.Open(); Console.Readline(); } } } public class Consumer() { public void ProcessTheRaisedEvent(object sender, MyEventArgs e) { Console.WriteLine(e.From.toString() + "\t" + e.To.ToString()); } } } namespace MyWCFNamespace { public delegate void SomeEventHandler(object sender,MyEventArgs e) [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class WCFService : IWCFService { public event SomeEventHandler WCFEvent; public void someMethod(Message message) { MyEventArgs e = new MyEventArgs(message); OnWCFEvent(e); } public void OnWCFEvent(MyEventArgs e) { SomeEventHandler handler = WCFEvent; if(handler!=null) { handler(this,e); } } // to do // Implement WCFInterface methods here } public class MyEventArgs:EventArgs { private Message _message; public MyEventArgs(Message message) { this._message=message; } } public class Message { string _from; string _to; public string From {get{return _from;} set {_from=value;}} public string To {get{return _to;} set {_to=value;}} public Message(){} public Message(string from,string to) this._from=from; this._to=to; } }
我们可以使用InstanceContextMode = InstanceContextMode.Single定义WCF服务。
TestService svc = new TestService(); svc.SomeEvent += new MyEventHandler(receivingObject.OnSomeEvent); ServiceHost host = new ServiceHost(svc); host.Open(); [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] // so that a single service instance is created public class TestService : ITestService { public event MyEventHandler SomeEvent; ... ... }