Note that there are some explanatory texts on larger screens.

plurals
  1. POChaining layers with IoC, setting lower callback to upper and avoid circular reference
    primarykey
    data
    text
    <p>I have a scenario where I need a lower layer to be controlled by an upper layer much like a puppet master pulling on strings.</p> <p>The lower layer also will call back to the upper layer as some internal events are generated from time to time.</p> <p>I am using SimpleInjector, I inject the ILower in to the Upper constructor. I cannot inject the Upper in to the Lower as it would cause a circular reference.</p> <p>Instead I have a register callback function to link the two layers. However, I have to scatter my code with null checks.</p> <p>Are there any nicer ways or different architectures to achieve this linking of objects?</p> <pre><code>// 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(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload