Forward Visibilty - Code Blog

Saturday, September 5, 2009

WCF Delegate in Silverlight 3.0

So it appears WCF in Silverlight operates like a singleton. This code below will actually fire the completed even 2 times, even though the async method was called once and the first service was disposed of.

void Page_Loaded(object sender, RoutedEventArgs e)
{
var svc= new UIService.UIServiceClient();
svc.GetXYZCompleted += GetXYZompleted;
svc=null;

var svc2= new UIService.UIServiceClient();
svc2.GetXYZCompleted += GetXYZompleted;
svc2.GetSpendDataAsync();
svc2=null;
}
Sure you can always just do a svc2.GetXYZCompleted -= GetXYZompleted; but it is just safer and cleaner code to put it in the constructor. Frequently it is not a problem to put it in the page load, because even your page load is only called one time. But if you use something like a tab control. Then each time you click on the tab the page load will get fired again. To be safe put them in the constructor, but remember you can't set break points on the constructor in Silverlight so debugging is a little more difficult.

Your code could look like this.
private void ConstructorCommon(MainPage mainPage)
{
InitializeComponent();
SetAllDelegates();
}

No comments:

Post a Comment