How to implement WCF ServiceModelEx Subscriber?

315 Views Asked by At

I'm using ServiceModelEx WCF library from Juval Lowy's "Programming WCF Services". I'm trying to implement a Publish-Subscribe Service with publisher and subscriber. What I have done so far is the publisher and the discover-publish service.

Service Contract:

[ServiceContract]
interface IMyEvents
{
    [OperationContract(IsOneWay=true)]
    void OnEvent1(int number);
}

Discover - publish Service:

class MyPublishService : DiscoveryPublishService<IMyEvents>, IMyEvents
{
    public void OnEvent1(int number)
    {
        FireEvent(number);
    }
}

Discover - publish service host:

ServiceHost host = DiscoveryPublishService<IMyEvents>.
CreateHost<MyPublishService>();
host.Open();
// later..
host.Close();

Publisher:

IMyEvents proxy = DiscoveryPublishService<IMyEvents>.CreateChannel();
proxy.OnEvent1();
(proxy as ICommunicationObject).Close();

My question is how can I implement the subscriber? The book says to implement the service contract. That's simple.

class EventServiceSubscriber : IMyEvents
{
    public void OnEvent1(int number)
    {
        // do something
    }
}

but how can i host the subscriber? How subscriber can connect to the Publish-Subscribe service?

2

There are 2 best solutions below

2
On

There are a bunch of articles around that cover this subject. For starters, this one. You can host your subscriber in different ways like a console application or a ASP.NET application. Every application type has some kind of startup method so that'd be a good place to implement your subscription/publishing logic.

1
On

To get this to work I created a SubcriptionService as follows:

using ServiceLibrary.Contracts;
using ServiceModelEx;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace Subscriber
{
    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any, IncludeExceptionDetailInFaults = DebugHelper.IncludeExceptionDetailInFaults, InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext = false)]
    class SubscriptionService : DiscoveryPublishService<IMyEvents>, IMyEvents
    {
        public void OnEvent1()
        {
            Debug.WriteLine("SubscriptionService OnEvent1");
        }

        public void OnEvent2(int number)
        {
            Debug.WriteLine("SubscriptionService OnEvent2");
        }

        public void OnEvent3(int number, string text)
        {
            Debug.WriteLine("SubscriptionService OnEvent3");
        }
    }
}

Then I set up a host for this service as follows:

ServiceHost<SubscriptionService> _SubscriptionHost = DiscoveryPublishService<IMyEvents>.CreateHost<SubscriptionService>();
_SubscriptionHost.Open();

A basic working sample can be found in my Github account at the following url.

https://github.com/systemsymbiosis/PublishSubscribeWithDiscovery