【问题标题】:Callback interface contract回调接口合约
【发布时间】:2013-01-08 05:40:13
【问题描述】:

我有两个需要受合同约束的 .NET 方。现在,party1 和party2 需要能够互相调用一些方法(大部分是调用和报告结果)。我有双工合同,但双方没有使用 WCF。

有这方面的设计模式吗?

编辑

各方是同一应用程序的一部分。我创建了应用程序 (party1),其他人创建了一个动态加载的 dll (party2)。现在,我们俩应该能够互相调用方法。所以,我要在我们之间创建一个接口契约。目的是知道是否有一个知道模式可以做到这一点?

【问题讨论】:

  • 如果他们不使用 WCF,他们是如何通信的?这种事情通常由支持会话的服务堆栈处理。
  • 这些部分是否只是编码单个应用程序的不同部分,直接调用彼此的程序集?如果是这样,接口(或抽象类)+代码契约(见msdn.microsoft.com/en-us/library/dd264808.aspx)可能是一个不错的选择
  • 此外,“经典”设计模式可能正在使用依赖注入 (martinfowler.com/articles/injection.html)。但实际上,如果没有更多信息和背景,很难说...
  • 各方是同一应用程序的一部分。我创建了应用程序 (party1),其他人创建了一个动态加载的 dll (party2)。现在,我们俩应该能够互相调用方法。所以,我要在我们之间创建一个接口契约。目的是知道是否有一个知道模式可以做到这一点?
  • 由于它们都在同一个 AppDomain 中,因此您可以使用常规的 pub/sub 模式,请在 this question 上查看我的答案。

标签: c# .net design-patterns interface contract


【解决方案1】:

一种常见的解决方案是使用某种发布/订阅模式。这样做可以避免循环依赖。

基本上,您创建某种用于订阅事件(并发布它们)的类。

所以你的两个班级都做了这样的事情(但有不同的事件):

public class ClassA : IEventHandler<UserCreated>
{
    IEventManager _eventManager

    public ClassA(IEventManager manager)
    {
       // I subscribe on this event (which is published by the other class)
       manager.Subscribe<UserCreated>(this);
       _eventManager = manager;
    } 

    public void Handle(UserCreated theEvent)
    {
        //gets invoked when the event is published by the other class
    }

    private void SomeInternalMethod()
    {
        //some business logic

        //and I publish this event
        _eventManager.Publish(new EmailSent(someFields));
    }
}

事件管理器(简化且不是线程安全的):

public class EventManager
{
    List<Subscriber> _subscribers = new List<Subscriber>();

    public void Subscribe<T>(IEventHandler<T> subscriber)
    {
        _subscribers.Add(new Subscriber{ EventType = typeof(T), Subscriber = subscriber});
    }

    public void Publish<T>(T theEvent)
    {
        foreach (var wrapper in subscribers.Where(x => x == typeof(theEvent)))
        {
            ((IEventHandler<T>)wrapper.Subscriber).Handle(theEvent);
        }
    }
}

小包装:

public class Subscriber
{
    public Type EventType;
    public object Subscriber;
}

瞧。这两个类现在彼此松散耦合(同时仍然能够相互通信)


如果您使用控制反转容器,它会变得更容易,因为您可以简化事件管理器并仅使用容器(服务位置)来解析所有订阅者:

public class EventManager
{
    IYourContainer _container;

    public EventManager(IYourContainer container)
    {
        _container = container;
    }

    public void Publish<T>(T theEvent)
    {
        foreach (var subscriber in _container.ResolveAll<IEventHandler<T>>())
        {
            subscriber.Handle(theEvent);
        }
    }
}

【讨论】:

  • 谢谢...我最终使用了控制容器反转的变体。
【解决方案2】:

我认为你可以使用下一个逻辑:

 Class1: Interface1 , Class2:Interface2, 

class Manager{
   public Manager(Interface1 managedPart1,Interface2 managedPart2){
        ... some logic for connect to interfaces
   }

}

这种方式让我想起Bridge的模式,但这是非常主观的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多