Loose Coupling – Advice on Loose Coupling Between User Controls in C#

asp.netc

I have 5 user controls on the page and each control implements it's own interface that contains properties and events. In order to enable communication between user controls, I am creating a property of target user control inside other user control. Through this property, it's state can be altered and be able to register its events.

Below is the pseudo code of results user control. It subscribes to OnSearch event of Search user control.

public interface IResults
{
     //other fields
    ISearch SearchControl { get;}
}

public partial class Results : IResults
{
 //other fields

 public ISearch SearchControl
 {

    get{
    this.Page.Parent.FindControl("UCSearch") as ISearch;}
 }

 protected override void Page_Load(object sender, EventArgs e)
 {
    this.SearchControl.OnSearch += new EventHandler(testMethod);
 }
}

Is it ok to have the reference properties inside user controls to subscribe to the events and manipulating the state. Does it create any maintenance problem in future.

Does FindControl and type casting degrade the performance of the application.

Best Answer

In general you might want to establish in your architecture, a rule of thumb that controls in your design will not know about other control(s). If they do, you can end up with spaghetti and cross-referencing difficulties. Consider introducing a Mediator, where only the Mediator knows about all the controls. If a control wants to talk to another control, it can do so only through the Mediator. The control raises an event, which is fielded by the Mediator. The Mediator has knowledge of what that event means to some other control on the page. It calls that control to do the work. The control that raised the event does not even know the other control exists.