I have a contextual object that has several useful properties and methods. Other objects accept this contextual object in their constructors. However, the contextual object can have these other objects as public properties. See below:
public class Foo {
private IContext Context { get; private set; }
public Foo( IContext context ) {
Context = context;
}
}
public class SomeContext : IContext {
public Foo SomeProperty { get; set; }
/*
Other useful properties and methods as defined in IContext
*/
public SomeContext () {
SomeProperty = new Foo( this );
}
}
Now I can do something useful in a method on Foo:
public void FooIt() {
IUseful bar = this.Context.GetUsefulInterface();
bar.DoUsefulThing();
}
However, it can lead to some really weird stuff. Consider these methods on Foo:
public void DoSomething() {
/* useful stuff */
}
public void DoSomethingElse() {
this.Context.SomeProperty.DoSomething(); // could just call this.DoSomething();
this.Context.SomeProperty.DoSomethingElse(); // stack overflow!
}
Is this considered a bad design / code smell? The reasons for the contextual object are somewhat involved, and I'd like to frame the question more towards the cyclical reference. If considered bad, what are some approaches to breaking this cyclical relationship?