Domanda

Voglio fare un semplice bus evento che permetterà a qualsiasi cliente di sottoscrivere un particolare tipo di evento e quando qualsiasi editore spinge un evento sul bus utilizzando il metodo EventBus.PushEvent() solo i clienti che hanno sottoscritto a quel particolare tipo di evento otterrà l'evento.

Sto usando C # e .NET 2.0.

È stato utile?

Soluzione 4

Ho trovato Generico Messaggio Bus . Si tratta di una semplice classe.

Altri suggerimenti

piccolo Messenger è una buona scelta, ho usato in un progetto live per 2,5 anni. Alcuni esempi di codice dalla (link sotto) Wiki:

Editoria

messageHub.Publish(new MyMessage());

Abbonamento

messageHub.Subscribe<MyMessage>((m) => { MessageBox.Show("Message Received!"); });
messageHub.Subscribe<MyMessageAgain>((m) => { MessageBox.Show("Message Received!"); }, (m) => m.Content == "Testing");

Il codice è su GitHub: https://github.com/grumpydev/TinyMessenger

Il Wiki è qui: https://github.com/grumpydev/TinyMessenger/wiki

Si ha un pacchetto Nuget anche

Install-Package TinyMessenger

Un altro, ispirato EventBus per Android, ma molto più semplice:

public class EventBus
{
    public static EventBus Instance { get { return instance ?? (instance = new EventBus()); } }

    public void Register(object listener)
    {
        if (!listeners.Any(l => l.Listener == listener))
            listeners.Add(new EventListenerWrapper(listener));
    }

    public void Unregister(object listener)
    {
        listeners.RemoveAll(l => l.Listener == listener);
    }

    public void PostEvent(object e)
    {
        listeners.Where(l => l.EventType == e.GetType()).ToList().ForEach(l => l.PostEvent(e));
    }

    private static EventBus instance;

    private EventBus() { }

    private List<EventListenerWrapper> listeners = new List<EventListenerWrapper>();

    private class EventListenerWrapper
    {
        public object Listener { get; private set; }
        public Type EventType { get; private set; }

        private MethodBase method;

        public EventListenerWrapper(object listener)
        {
            Listener = listener;

            Type type = listener.GetType();

            method = type.GetMethod("OnEvent");
            if (method == null)
                throw new ArgumentException("Class " + type.Name + " does not containt method OnEvent");

            ParameterInfo[] parameters = method.GetParameters();
            if (parameters.Length != 1)
                throw new ArgumentException("Method OnEvent of class " + type.Name + " have invalid number of parameters (should be one)");

            EventType = parameters[0].ParameterType;
        }

        public void PostEvent(object e)
        {
            method.Invoke(Listener, new[] { e });
        }
    }      
}

Caso d'uso:

public class OnProgressChangedEvent
{

    public int Progress { get; private set; }

    public OnProgressChangedEvent(int progress)
    {
        Progress = progress;
    }
}

public class SomeForm : Form
{
    // ...

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        EventBus.Instance.Register(this);
    }

    public void OnEvent(OnProgressChangedEvent e)
    {
        progressBar.Value = e.Progress;
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        EventBus.Instance.Unregister(this);
    }
}

public class SomeWorkerSomewhere
{
    void OnDoWork()
    {
        // ...

        EventBus.Instance.PostEvent(new OnProgressChangedEvent(progress));

        // ...
    }
}

Si potrebbe anche verificare le estensioni Unity: http://msdn.microsoft.com/en-us/library/cc440958. aspx

[Publishes("TimerTick")]
public event EventHandler Expired;
private void OnTick(Object sender, EventArgs e)
{
  timer.Stop();
  OnExpired(this);
}

[SubscribesTo("TimerTick")]
public void OnTimerExpired(Object sender, EventArgs e)
{
  EventHandler handlers = ChangeLight;
  if(handlers != null)
  {
    handlers(this, EventArgs.Empty);
  }
  currentLight = ( currentLight + 1 ) % 3;
  timer.Duration = lightTimes[currentLight];
  timer.Start();
}

sono quelli là migliori?

Il Composite Application Block include un broker evento che potrebbe essere utile a voi.

Un altro buon applicazione è disponibile all'indirizzo:

http://code.google .com / p / frattura / source / browse / trunk / Squared / Util / EventBus.cs

I casi d'uso è accessibile a: /trunk/Squared/Util/UtilTests/Tests/EventTests.cs

Questa implementazione non ha bisogno di libreria esterna.

Un miglioramento potrebbe essere quello di essere in grado di iscriversi con un tipo e non una stringa.

Si dovrebbe verificare episodio 3 in Hibernating Rhinos , schermo di Ayende getta serie - "Implementazione il broker evento".

Essa mostra come è possibile implementare un semplice mediatore evento utilizzando Windsor a cablare le cose. Il codice sorgente è incluso pure.

La soluzione mediatore evento proposto è molto semplice, ma non avrebbe preso troppe ore per aumentare la soluzione per consentire argomenti da passare insieme con gli eventi.

Ho creato questo:

https://github.com/RemiBou/RemiDDD/tree/ master / RemiDDD.Framework / Cqrs

C'è una dipendenza con Ninject. Hai un MessageProcessor. Se si vuole obsere un evento, attuare "IObserver", se si desidera gestire un comando attuare "ICommandHandleer"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top