Rati_Ge
Rati_Ge

Reputation: 1270

Declare method in interface

I have an interface INetworkAware and need to declare method which will forece every class to register for events

currently using prisms eventaggregator our implementation is the following.

    protected override void SetupEvents()
    {
        RegisterForEvent<PatientSelected>(OnPatientSelected);
        base.SetupEvents();
    }

SetupEvents method is declared as virtual in ViewModelbase class. in out situation we want to have above mentioned INetworkAware interface and in addition to deriving from ViewModelBase if any class is interested in listening to network changes(network offline/online) and implement INetworkAware interface we want to have mechanism to force them to register for this event using same principals. so for example if we create class

public class PatientInformationViewModel : ViewModelBase, INetworkAware
{
     protected override void SetupEvents()
     {
         RegisterForEvent<PatientSelected>(OnPatientSelected);
         base.SetupEvents();
     }

     INetworkAware.ListenForNetworkChange
     {
         RegisterForEvent<NetworkChangeEvent>(OnNetworkChange)
     }

     OnNetworkChange(NetworkChangeEvent networkstatus)
     {

     }
 }

NetworkChangeEvent is a sample POCO class

INetworkAware.ListenForNetworkChange and OnNetworkChange(NetworkChangeEvent networkstatus) must be implemented in every viewmodel deriving from INetworkaware and with the same signature.

houw can we accomplish this scenario

Upvotes: 1

Views: 297

Answers (1)

slugster
slugster

Reputation: 49985

You are almost on the right track. If you implement the interface on the base class and then declare your method as abstract in the base class that will force any extending (deriving) class to implement it's own version:

public abstract class ViewModelBase : INetworkAware
{

    public abstract void SetupEvents();

}

public class PatientInformationViewModel : ViewModelBase
{
    public override void SetupEvents()
    {
        //register for your events
    }
}

Alternatively you can declare the method in the base class as virtual rather than abstract and provide a base implementation, and your derived classes can simply override this when necessary. I've used this pattern before myself and it is quite effective - just make sure you include an Unsubscribe() (or similar) on the interface as well.

Upvotes: 2

Related Questions