This entry is part 3 of 6 in the series WCF Publish Subscribe - A Full Example in C#, Step by Step

Our implementation is based on .NET events (for a non-events based implementation, check out the New IObserver IObservable interfaces in C# 4.0). The idea of publishing goes hand-in-hand with ‘raising an event’  – and the idea of subscribers goes hand-in-hand with consuming an event.

Our event based implementation thus consists of:

  1. Defining an event
  2. Defining an  event handler (all the handler will do is notify the various subscribers)
  3. Implement the Subscribe method
  4. Implement the Unsubscribe method
  5. Implement the PublishMagazine method
public class NewIssueAvailableEventArgs : EventArgs

{

    public string hyperlinkURL;

    public string issueNumber;

    public DateTime datePublished;

}

 

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

public class MagazineService : IMagazineService

{

    public static event NewIssueAvailableHandler NewIssueAvailableEvent;

    public delegate void NewIssueAvailableHandler(object sender, NewIssueAvailableEventArgs e);

 

    // instance of eventhandler

    NewIssueAvailableHandler newIssueHandler;

 

    // Callback to individual clients using the ClientContract

    IClientContract callback = null;

 

    public void PublishMagazine(string hyperLinkToIssue, string issueNumber, DateTime datePublished)

    {

        NewIssueAvailableEventArgs eargs = new NewIssueAvailableEventArgs();

        eargs.hyperlinkURL = hyperLinkToIssue;

        eargs.issueNumber = issueNumber;

        eargs.datePublished = datePublished;

 

        // fire the event

        NewIssueAvailableEvent(this, eargs);

    }

 

    public void Subscribe()

    {

        callback = OperationContext.Current.GetCallbackChannel<IClientContract>();

        // this is the handler that we will 'unsubscribe' from later

        newIssueHandler = new NewIssueAvailableHandler(MagazineService_NewIssueAvailableEvent);

        NewIssueAvailableEvent += newIssueHandler;

    }

 

    public void Unsubscribe()

    {

        NewIssueAvailableEvent -= newIssueHandler;

    }

 

    public void MagazineService_NewIssueAvailableEvent(object sender, NewIssueAvailableEventArgs e)

    {

        callback.MessageReceived(e.hyperlinkURL, e.issueNumber, e.datePublished);

    }

}

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.


Series NavigationWCF Publish Subscribe–A Full Example – The Service Side Part 1 (Interface)WCF and Publish Subscribe–A Full Example: The Event Generator