[已解决]从WCF主机发布自定义事件 [英] [SOLVED] Post Custom Event from WCF Host

查看:91
本文介绍了[已解决]从WCF主机发布自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已创建的WCF服务,当客户端调用其中一种服务方法时,我想将一个事件从服务主机发布到实例化该应用的应用(不发布至客户端应用),并拥有处理这些事件的应用程序.我试过了:

I have a WCF service that I''ve created, and when a client calls one of the service methods, I want to post an event from the service host to the app that instantiated it (NOT to the client app), and have the app that handle those events. I tried this:

public class MyService : IMyService
{
    // this is a standard custom event
    public event MyHostEventHandler MyHostEvent = delegate { };

    //--------------------------------------------------------------------------------
    public void SendStatusMessage(string msg)
    {
        MyHostEvent(this, new MyHostEventArgs(msg, DateTime.Now));
    }

    //--------------------------------------------------------------------------------
    public void SendStatusMessage(string msg, DateTime datetime)
    {
        MyHostEvent(this, new MyHostEventArgs(msg, datetime));
    }
}



但是,当我创建服务宿主对象时,在智能感知中看不到我的事件.我会以错误的方式处理吗?我错过了一步吗?有一些WCF导入机制可以做到这一点吗?有没有可以用来启用此功能的元标记?

我接下来要尝试的事情是指定委托以回调可以发送事件的静态类.



But when I create the service host object, I don''t see my event in intellisense. Am I going about this the wrong way? Am I missing a step? Is there some WCF bult-in mechanism for doing this? Is there a metatag I can use to enable this?

My next thing to try is specifying delegates to call back to a static class that can post the event instead.

推荐答案

John,

为此,您的服务必须是单例服务.否则,您将无法控制随时使用的服务类的实例.

并且一旦有了单例服务,就可以使用SingletonInstance 属性(需要将其强制转换为服务类型),然后访问事件(并挂接处理程序).
John,

For this to work, your service has to be a singleton service. Otherwise you have no control over the instance of the service class that''s being used at any time.

And once you have a singleton service, you can use the SingletonInstance property (you''ll need to cast it to your service type) and then access the event (and hook a handler).


虽然Nish的回答将我引向了正确的方向,但更精确的解决方案是在服务声明中添加以下属性:

While Nish''s answer steered me in the right direction, the more precise solution was to add the following attribute to the service declaration:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]


这篇关于[已解决]从WCF主机发布自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆