【问题标题】:Event-delegate analogy in WCFWCF 中的事件委托类比
【发布时间】:2012-06-26 14:21:42
【问题描述】:

我有实现 MVC 模式的 WinForms 应用程序,其中模型从视图(窗体)异步运行(后台工作线程)。 View 订阅了从 Model 引发的几个事件。

现在我需要将其转换为 WCF 应用程序,其中必须存在 event-eventHandler 概念。
起初,我想通过回调接口来实现这一点,但在我的例子中,模型中的一个方法引发了不止一种类型的事件,并且在定义服务合同时我受限于单个回调接口的使用。

此时我想到了在回调服务中指定不同类型的事件作为方法并在客户端实现它的想法。例如:

public interface ICallbacks
{
  [OperationContract(IsOneWay = true)]
  void EventHandler1();

  [OperationContract(IsOneWay = true)]
  void EventHandler2(string callbackValue);

  [OperationContract(IsOneWay = true)]
  void EventHandler3(string callbackValue);
}

我应该接受这个解决方案还是有一些更好的选择(发布-订阅 wcf 模式)?

【问题讨论】:

    标签: c# .net wcf


    【解决方案1】:

    听起来您肯定想要这里的 pub/sub 架构。

    从这篇 MSDN 文章中了解 Juval Lowy 的发布-订阅框架: http://msdn.microsoft.com/en-us/magazine/cc163537.aspx

    【讨论】:

      【解决方案2】:

      您可以使用带有基本类型参​​数的单一方法来激活您的调用。然后在您的服务代码中,根据事件的类型跳转到特定的处理程序。

      public class BaseEvent { }
      
      public class MyFirstEvent : BaseEvent { }
      
      public class MySecondEvent : BaseEvent { }
      
      public class MyThirdEvent : BaseEvent { }
      
      
      public interface ICallbacks
      {
        [OperationContract(IsOneWay = true)]
        void EventHandler(BaseEvent myEvent);
      }
      
      public class MyService : ICallbacks
      {
         public void EventHandler(BaseEvent myEvent)
         {
            //Now you can check for the concrete type of myEvent and jump to specific method.
            //e.g.: 
            if (myEvent is MyFirstEvent)
            {
               //Call your handler here.
            }
      
      
            //Another approach can be predefined dictionary map of your event handlers
            //You want to define this as static map in class scope, 
            //not necessarily within this method.
            Dictionary<Type, string> map = new Dictionary<Type, string>()
            {
               { typeof(MyFirstEvent), "MyFirstEventHandlerMethod" },
               { typeof(MySecondEvent), "MySecondEventHandlerMethod" }
               { typeof(MyThridEvent), "MyThirdEventHandlerMethod" }
            };
      
            //Get method name from the map and invoke it.
            var targetMethod = map[myEvent.GetType()];
            this.GetType().GetMethod(targetMethod).Invoke(myEvent);
         }
      }
      

      【讨论】:

        【解决方案3】:

        使用双工不是一个好主意,除非您的应用程序至少在同一网络上运行在同一网络上,并且没有代理等干扰。您还将最终在发布者和订阅者之间实现紧密耦合。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-18
          相关资源
          最近更新 更多