dimanche 22 novembre 2015

Is this pattern for subscribing to events okay?

I want to have a logger which is "made available" to my application. My application logs interesting things, and subscribers subscribe to those messages. For example a subscriber might put message in a database, or the windows event log, or a message bus, etc.

A simplified reproduction of what I've written is below:

using System;
using System.Reactive.Subjects;

namespace ConsoleApplication17
{
    internal interface ILogger
    {
        void Log(String message);
    }

    internal class Logger : ILogger
    {
        private readonly Subject<String> _logMessagesObservable = new Subject<string>();

        public void Log(string json)
        {
            _logMessagesObservable.OnNext(json);
        }

        public IObservable<String> LogMessagesObservable { get { return _logMessagesObservable; } }
    }

    internal class ConsoleLogListener
    {
        public ConsoleLogListener(IObservable<String> messages)
        {
            messages.Subscribe(Console.WriteLine);
        }
    }

    internal class WindowsEventListener
    {
        public WindowsEventListener(IObservable<String> messages)
        {
            messages.Subscribe(WriteToEventLog);
        }

        private void WriteToEventLog(String message)
        {
            //Write to event log
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();

            //Link up any subscribers
            new ConsoleLogListener(logger.LogMessagesObservable);
            new WindowsEventListener(logger.LogMessagesObservable);
            //... more listeners go here.           

            DoSomeWork(logger);
        }

        private static void DoSomeWork(ILogger logger)
        {
            logger.Log("Something interesting");
            logger.Log("Something else interesting");
        }
    }
}

But I'm not happy about the code which looks like this:

//Link up any subscribers
new ConsoleLogListener(logger.LogMessagesObservable);
new WindowsEventListener(logger.LogMessagesObservable);
//... more listeners go here. 

It irks me for some reason but I can't put my finger on it. I guess it just looks odd to new up a listener like that and not keep the reference to it.

Is there a better / more accepted pattern for what I'm trying to do?

Aucun commentaire:

Enregistrer un commentaire