WCF Event Declaration

前端 未结 1 1769
無奈伤痛
無奈伤痛 2021-01-14 10:03

I see that WCF doesn\'t directly use events and instead uses OneWay delegate calls, but can someone show me a simple example on how to do this?

Here is what I have s

1条回答
  •  走了就别回头了
    2021-01-14 10:33

    Assuming your callback contract interface is called IMyServiceCallback, your service would execute the following code when it wanted to raise the event:

    IMyServiceCallback callback = OperationContext.Current.GetCallbackChannel();
    callback.OnGetMapStoryboardsComplete(...);
    

    I found this article very helpful. It describes a transient event system and a persisted event system, either of which should satisfy any and all event scenarios, IMO.

    HTH

    To set up the callback contract:

    interface IMyServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void OnGetMapStoryboardsComplete(object sender, List);
    }
    

    Then you need to indicate on your service contract that it is using this callback:

    [ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
    interface IMyService
    {
        // ...
    }
    

    Once you have done that and implemented your service, create a reference to the service. The client will then have to include a class that implements IMyServiceCallback:

    class EventHandler : IMyServiceCallback
    {
        public void OnGetMapStoryBoardsComplete(object sender, List)
        {
            // Do whatever needs to be done when the event is raised.
        }
    }
    

    When you connect from the client to the service you need to pass it an InstanceContext built with a reference to the object that will handle the events:

    EventHandler eventHandler = new EventHandler();
    MyServiceClient client = new MyServiceClient(new InstanceContext(eventHandler));
    

    Does that make sense?

    0 讨论(0)
提交回复
热议问题