Skip to content

Instantly share code, notes, and snippets.

@michaelnoonan
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelnoonan/97777eb445235cb5428a to your computer and use it in GitHub Desktop.
Save michaelnoonan/97777eb445235cb5428a to your computer and use it in GitHub Desktop.
Attribute Routing for Nimbus
[AttributeUsage(AttributeTargets.Class)]
public class AppServerCommandRouteAttribute : Attribute
{
public AppServerCommandRouteAttribute(string route)
{
if (string.IsNullOrWhiteSpace(route)) throw new ArgumentNullException("route");
Route = ("appserver." + route).ToLowerInvariant();
}
public string Route { get; private set; }
}
public class AppServerMessageRouter : IRouter
{
internal static readonly string AppServerCommandsQueue = "appserver.commands";
internal static readonly string AppServerRequestsQueue = "appserver.requests";
//internal static readonly string AppServerEventsTopic = "appserver.events";
public bool CanRoute(Type messageType)
{
return messageType.IsBusMessage();
}
public string Route(Type messageType, QueueOrTopic queueOrTopic)
{
if (messageType.IsBusCommand())
{
var commandRouteAttribute = messageType.GetCustomAttribute<AppServerCommandRouteAttribute>();
return commandRouteAttribute != null ? commandRouteAttribute.Route : AppServerCommandsQueue;
}
if (messageType.IsBusRequest())
return AppServerRequestsQueue;
if (messageType.IsBusEvent())
return PathFactory.TopicPathFor(messageType);
//return AppServerEventsTopic;
throw new Exception("Cannot build a route for the message type '{0}'.".FormatWith(messageType.FullName));
}
}
public class DelegatingRouter : IRouter
{
private readonly IEnumerable<IRouter> _routers;
public DelegatingRouter(IEnumerable<IRouter> routers)
{
_routers = routers;
}
public string Route(Type messageType, QueueOrTopic queueOrTopic)
{
//Terrible, fix it.
var router = _routers.FirstOrDefault(x => ((dynamic)x).CanRoute(messageType) == true);
if (router == null)
throw new RoutingException("Unable to find a router for message type {0}".FormatWith(messageType.FullName));
return router.Route(messageType, queueOrTopic);
}
}
.WithRouter(new DelegatingRouter(new IRouter[]
{
new AppServerMessageRouter()
}))
public class QueuedCommunicationCommandRouteAttribute : AppServerCommandRouteAttribute
{
public QueuedCommunicationCommandRouteAttribute()
: base("queuedcommunication")
{
}
}
public class RoutingException : Exception
{
public RoutingException(string message)
: base(message)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment