我有一个托管WCF服务的控制台应用程序。我希望能够从WCF服务中的方法触发事件,并在WCF服务的托管过程中处理事件。这可能吗?我该怎么做?我可以从ServiceHost派生自定义类吗?
答案 0 :(得分:14)
您无需继承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
中所述或者你可以有一个众所周知的单例类,你的服务实例知道并在事件发生时显式调用它的方法。
答案 1 :(得分:0)
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;
...
...
}