I am consuming WCF services from a Silverlight application (MVVM) and windows phone. I have a Service class (Auto-generated) and one IServiceRepository looks like the following
public interface IServiceRepository
{
event EventHandler<SomeEventArgs> GetDataCompleted;
void Data GetData();
// 10 more methods for fetching different data.
}
My SerViceRepository looks like the following
public class ServiceRepository : IServiceRepository
{
public event EventHandler<SomeEventArgs> GetDataCompleted;
public void Data GetData()
{
var proxy = new ActualServiceRefClient();
proxy.GetDataCompleted += PrivateGetDataCompleted;
proy.GetDatAsync();
}
private void PrivateGetDataCompleted(object s, SomeEventArgs e)
{
// Error check and all
if(GetDataCompleted != null)
GetDataCompleted(this, new SomeEventArgs(...));
}
}
I am calling this methods from my ViewModels. Now my questions are …
- Right now I am creating the proxy
class and attaching event handler
with it in every method. Should I do
it in the constructor of
ServiceRepository? As I said I have
around 10 to 12 service methods to
call. - Should I unregister the event handler in the completed method?
I’m not sure it matters where it goes. If you have just one one actual service method you are calling, putting the event wiring in the constructor makes sense. If there is one actual service method for each of the 10 data methods in your service repository, then it makes more sense to have them wired up in each of the 10-12 individual methods.
It depends. If you are keeping an instance of the Service Repository around, making several calls to it, then you should either move the event wiring to the constructor, or make sure you don’t re-wire the event handler on each call. Alternatively, you CAN unregister as you said, but I think it’s best to register those event handlers once for the lifetime of the object. If you are simply creating a new instance of your Service Repository for each can, there is no need to unregister the event handlers.
Hope this helps!