我有一个托管 WCF 服务的控制台应用程序。我希望能够从 WCF 服务中的方法触发事件并在 WCF 服务的托管过程中处理该事件。这可能吗?我该怎么做?我可以从 ServiceHost 派生一个自定义类吗?
dotnetengineer
问问题
8604 次
2 回答
15
您不需要继承自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中所述
或者你可以有一个众所周知的单例类,你的服务实例知道并在事件发生时显式调用它的方法。
于 2008-09-26T14:30:05.380 回答
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
.
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;
...
...
}
于 2010-11-28T06:14:30.720 回答