Created
August 28, 2017 12:43
-
-
Save romeshniriella/f9ed69de4b35d724ac2be3a729d9c001 to your computer and use it in GitHub Desktop.
simple event handler base class for Rx with masstransit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MassTransit; | |
using Core.Runtime.Events; | |
using Core.Runtime.Events.Tracking.Contracts; | |
using Core.Runtime.Logging; | |
using Core.Utils.Extensions; | |
namespace Oklo.Shared.Runtime | |
{ | |
public abstract class EventHandlerBase | |
{ | |
protected readonly IBusControl MessageBus; | |
protected readonly ISystemLogger Logger; | |
public static EventBus EventBus => EventBus.Instance; | |
protected EventHandlerBase(IBusControl bus, ISystemLogger logger) | |
{ | |
MessageBus = bus; | |
Logger = logger; | |
} | |
protected virtual void Handle<T>(Action<T> handler = null) where T : IApplicationEvent | |
{ | |
EventBus.GetEvent<T>().Subscribe(delegate (T obj) | |
{ | |
if (handler != null) | |
{ | |
LogEvent(handler.Method.Name, obj); | |
handler(obj); | |
} | |
else | |
{ | |
LogEvent(obj); | |
} | |
}, | |
exception => Logger.Error("Event handler resulted an error", exception) | |
); //, () => _logger.Info("handler executed successfully!") | |
} | |
protected virtual void Handle<T>(Action<T> handler, Action onCompleted) where T : IApplicationEvent | |
{ | |
EventBus.GetEvent<T>().Subscribe(delegate (T obj) | |
{ | |
LogEvent(handler.Method.Name, obj); | |
handler(obj); | |
}, | |
exception => Logger.Error("Event handler resulted an error", exception) | |
, onCompleted); | |
} | |
protected virtual void LogEvent(IApplicationEvent obj) | |
{ | |
LogEvent(obj.GetType().Name, obj); | |
} | |
protected virtual void LogEvent(string name, IApplicationEvent obj) | |
{ | |
Logger.DebugFormat("{0}:[{2}]:{1}", name, obj.Json(), obj.GetType().Name); | |
} | |
public abstract void SubscribeToEvents(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IApplicationEvent | |
{ | |
DateTime TimeStamp { get; } | |
string EventId { get; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment