1
0
mirror of https://github.com/Radarr/Radarr.git synced 2024-11-05 02:22:31 +01:00
Radarr/NzbDrone.Common/Messaging/MessageAggregator.cs

100 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Reflection;
using System.Threading.Tasks;
2013-02-23 21:09:44 +01:00
using NLog;
2013-05-11 01:53:50 +02:00
using NzbDrone.Common.Composition;
namespace NzbDrone.Common.Messaging
{
2013-05-11 01:53:50 +02:00
[Singleton]
public class MessageAggregator : IMessageAggregator
{
2013-02-23 21:09:44 +01:00
private readonly Logger _logger;
private readonly IServiceFactory _serviceFactory;
public MessageAggregator(Logger logger, IServiceFactory serviceFactory)
{
2013-02-23 21:09:44 +01:00
_logger = logger;
_serviceFactory = serviceFactory;
}
public void PublishEvent<TEvent>(TEvent @event) where TEvent : IEvent
{
2013-05-11 22:06:57 +02:00
var eventName = GetEventName(@event.GetType());
_logger.Trace("Publishing {0}", eventName);
//call synchronous handlers first.
foreach (var handler in _serviceFactory.BuildAll<IHandle<TEvent>>())
{
try
{
2013-05-11 22:06:57 +02:00
_logger.Debug("{0} -> {1}", eventName, handler.GetType().Name);
handler.Handle(@event);
2013-05-11 22:06:57 +02:00
_logger.Debug("{0} <- {1}", eventName, handler.GetType().Name);
}
catch (Exception e)
{
2013-05-11 22:06:57 +02:00
_logger.ErrorException(string.Format("{0} failed while processing [{1}]", handler.GetType().Name, eventName), e);
}
}
foreach (var handler in _serviceFactory.BuildAll<IHandleAsync<TEvent>>())
{
var handlerLocal = handler;
Task.Factory.StartNew(() =>
{
2013-05-11 22:06:57 +02:00
_logger.Debug("{0} ~> {1}", eventName, handlerLocal.GetType().Name);
handlerLocal.HandleAsync(@event);
2013-05-11 22:06:57 +02:00
_logger.Debug("{0} <~ {1}", eventName, handlerLocal.GetType().Name);
});
}
}
2013-05-11 22:06:57 +02:00
private static string GetEventName(Type eventType)
{
if (!eventType.IsGenericType)
{
return eventType.Name;
}
return string.Format("{0}<{1}>", eventType.Name.Remove(eventType.Name.IndexOf('`')), eventType.GetGenericArguments()[0].Name);
}
public void PublishCommand<TCommand>(TCommand command) where TCommand : ICommand
{
var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType());
_logger.Trace("Publishing {0}", command.GetType().Name);
var handler = _serviceFactory.Build(handlerContract);
_logger.Debug("{0} -> {1}", command.GetType().Name, handler.GetType().Name);
2013-05-11 22:06:57 +02:00
try
{
handlerContract.GetMethod("Execute").Invoke(handler, new object[] {command});
PublishEvent(new CommandCompletedEvent(command));
}
catch (TargetInvocationException e)
{
PublishEvent(new CommandFailedEvent(command, e));
if (e.InnerException != null)
{
throw e.InnerException;
}
throw;
}
finally
{
PublishEvent(new CommandExecutedEvent(command));
}
_logger.Debug("{0} <- {1}", command.GetType().Name, handler.GetType().Name);
}
}
}