我有一个场景,我需要下层由上层控制,就像木偶大师拉弦一样。
由于不时产生一些内部事件,下层也会回调上层。
我正在使用 SimpleInjector,我将 ILower 注入到 Upper 构造函数中。我不能将 Upper 注入到 Lower 中,因为它会导致循环引用。
相反,我有一个注册回调函数来链接两个层。但是,我必须使用空检查来分散我的代码。
有没有更好的方法或不同的架构来实现对象的这种链接?
// an interface that transport can callback from transport to client
public interface ILowerToUpperCallback
{
    void ReplyA();
    void ReplyB();
}
// transport interface that client calls
public interface ILower
{
    void Test1();
    void Test2();
    void RegisterCallback(ILowerToUpperCallback callback);
}
public class Upper : ILowerToUpperCallback
{
    private readonly ILower lower;
    public Upper(ILower lower)
    {
        this.lower = lower;
        this.lower.RegisterCallback(this);
    }
    void ReplyA()
    {
    }
    void ReplyB()
    {
    }
}
public class Lower : ILower
{
    private ILowerToUpperCallback callback;
    /* this is not possible, would cause a circular reference
    public Lower(ILowerToUpperCallback callback)
    {
        this.callback = callback;
    }
    */
    // set by different method instead, what happens if this is never set?!
    void RegisterCallback(ILowerToUpperCallback callback)
    {
        this.callback = callback;
    }
    void OnTimer()
    {
        // some timer function
        if(this.callback != null) // these null checks are everywhere :(
            this.callback.ReplyA();
    }
}