.NET를위한 간단한 이벤트 버스 [폐쇄
문제
모든 고객이 특정 유형의 이벤트를 구독 할 수있는 매우 간단한 이벤트 버스를 만들고 싶습니다. EventBus.PushEvent()
방법 특정 이벤트 유형에 가입 한 클라이언트만이 이벤트를 얻습니다.
C# 및 .NET 2.0을 사용하고 있습니다.
해결책 4
나는 찾았다 일반 메시지 버스 . 하나의 간단한 수업입니다.
다른 팁
Tiny Messenger는 좋은 선택입니다. 저는 2.5 년 동안 라이브 프로젝트에서 사용해 왔습니다. 위키의 일부 코드 예제 (아래 링크) :
출판
messageHub.Publish(new MyMessage());
가입
messageHub.Subscribe<MyMessage>((m) => { MessageBox.Show("Message Received!"); });
messageHub.Subscribe<MyMessageAgain>((m) => { MessageBox.Show("Message Received!"); }, (m) => m.Content == "Testing");
코드는 Github에 있습니다. https://github.com/grumpydev/tinymessenger
위키가 여기에 있습니다. https://github.com/grumpydev/tinymessenger/wiki
Nuget 패키지도 있습니다
Install-Package TinyMessenger
Android 용 Eventbus에서 영감을 얻은 또 다른 하나는 훨씬 간단합니다.
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 });
}
}
}
유스 케이스 :
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));
// ...
}
}
Unity Extensions를 확인할 수도 있습니다.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();
}
더 나은 것이 있습니까?
그만큼 복합 응용 프로그램 블록 당신에게 사용할 수있는 이벤트 브로커가 포함되어 있습니다.
또 다른 좋은 구현은 다음에서 찾을 수 있습니다.
http://code.google.com/p/fracture/source/browse/trunk/squared/util/eventbus.cs
사용 사례는 /trunk/squared/util/utiltests/tests/eventtests.cs에서 액세스 할 수 있습니다
이 구현에는 외부 라이브러리가 필요하지 않습니다.
개선은 문자열이 아닌 유형으로 구독 할 수있는 것일 수 있습니다.
에피소드 3 인치를 확인해야합니다 최대 근무 코뿔소, Ayende의 스크린 캐스트 시리즈 - "이벤트 브로커 구현".
Windsor를 사용하여 매우 간단한 이벤트 브로커를 구현하여 물건을 연결하는 방법을 보여줍니다. 소스 코드도 포함되어 있습니다.
제안 된 이벤트 브로커 솔루션은 매우 간단하지만 이벤트와 함께 인수를 전달할 수 있도록 솔루션을 증강시키는 데 너무 많은 시간이 걸리지 않습니다.
나는 이것을 만들었다 :
https://github.com/remibou/remiddd/tree/master/remiddd.framework/cqrs
Ninject와 의존성이 있습니다. 당신은 메시지 프로세서를 받았습니다. 이벤트를 관찰하려면 "iobserver"를 구현하려면 "iobserver"를 구현하려면 "Icommandhandleer"를 구현하려면