views:

34

answers:

1

Hello all. I have been struggling with this question for awhile now, and I haven't reached a conclusion. I'm not typically a UI programmer, so forgive the noobishness.

I'm writing a typical application with a UI layer (WPF) and a business layer. I want to post status messages to the UI from the business layer (perhaps deep within the business layer), but I don't want the business layer to have any knowledge of the UI. Is there a generally accepted pattern for this?

I was thinking to have a message queue of some sort to which the business layer posts status messages, and have the view model of the UI subscribe to that queue and intercept messages from the queue and route them to the UI. Is that a good approach? Is there somewhere else I should start?

Thank you.

+1  A: 

I think that's a good approach in general. I would create an interface for your message provider that publishes an event when a message is received (Where Message is the message type you want):

public class MessageReceivedEventArgs : EventArgs
{
    public MessageReceivedEventArgs(Message message)
        : base()
    {
        Message = message;
    }

    public Message Message { get; set; }
}

public delegate void MessageRecievedHandler(object sender, MessageReceivedEventArgs e);

public interface IMessageProvider
{
    event MessageRecievedHandler MessageReceived;
    void Start();
    void Stop();
    bool IsRunning { get; }
}

public abstract class MessageProviderBase : IMessageProvider
{
    public event MessageRecievedHandler MessageReceived;

    public MessageProviderBase()
    {}

    protected void OnMessageReceived(MessageReceivedEventArgs e)
    {
        if (MessageReceived != null)
        {
            MessageReceived(this, e);
        }
    }

    public abstract void Start();
    public abstract void Stop();

    public abstract bool IsRunning { get; }
}
Jeremy Bell
cool! thanks for the code jeremy. i'm gonna digest it now.
generalt
it seems like the classes deriving from MessageProviderBase should be a singleton?
generalt
It's possible, but not necessary. The MessageProviderBase is there for convenience just to provide the OnMessageReceived method to potential IMessageProviders, though you don't strictly need to derive from it to implement IMessageProvider.PS: If you derive from MessageProviderBase, it's best to also list your class as implementing IMessageProvider, so as not to confuse WPF's xaml parser (if you're going that route): public class CustomMessageProvider : MessageProviderBase, IMessageProvider
Jeremy Bell
awesome, thanks jeremy. i'm gonna go mess around with this.
generalt
don't forget to mark this as the answer so it doesn't show up in the unanswered list.
Jeremy Bell
thanks for the heads up jeremy. i didn't know about that functionality. i'm a stack overflow noob as well. :D
generalt