Tags: , | Categories: Software Development Posted by bjarte.skogoy on 5/7/2010 8:11 AM | Comments (0)

I’ve been using Rhino Service Bus in some projects and needed a way to bridge it with synchronous WCF calls. Here’s the code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rhino.ServiceBus.Sagas;
using Rhino.ServiceBus;
using System.Threading;
using Rhino.ServiceBus.Internal;

namespace Rhino.ServiceBus
{
    public static class ReplyExtension
    {
        class ESBResult<R> : OccasionalConsumerOf<R>, IDisposable
        {
            ManualResetEvent waithandle;
            IServiceBus bus;
            IDisposable subscription;
            TimeSpan patience;

            public ESBResult(IServiceBus bus, ISagaMessage message, TimeSpan patience)
            {
                this.bus = bus;

                this.patience = patience;
                waithandle = new ManualResetEvent(false);
                subscription = bus.AddInstanceSubscription(this);
                bus.Send(message);
            }

            public ESBResult(IServiceBus bus, ISagaMessage message)
                : this(bus, message, TimeSpan.FromSeconds(5))
            {
            }

            public R Reply
            {
                get
                {
                    waithandle.WaitOne(patience);
                    return m_Reply;
                }
            }

            #region ConsumerOf<R> Members

            R m_Reply = default(R);
            public void Consume(R message)
            {
                m_Reply = message;
                waithandle.Set();
            }

            #endregion

            #region IDisposable Members

            public void Dispose()
            {
                var b = bus;
                subscription.Dispose();
            }

            #endregion
        }

        public static R SendAndWaitForReply<R>(this IServiceBus bus, ISagaMessage message)
        {
            using (var result = new ESBResult<R>(bus, message))
                return result.Reply;
        }
    }
}

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading