Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chilversc
Last active August 29, 2015 14:07
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 chilversc/76246924d25fe6fc1b48 to your computer and use it in GitHub Desktop.
Save chilversc/76246924d25fe6fc1b48 to your computer and use it in GitHub Desktop.
Rebus automatic message subscribtion
#define NONEST
RebusBus bus = new RebusBus ();
WindsorContainer container;
void Main()
{
BuildContainer ();
Subscribe (bus, container.Kernel);
bus.subscribed.Dump ();
container.ResolveAll<IHandleMessages<E1>> ().Dump ();
container.Kernel.GetHandlers(typeof (IHandleMessages<E1>))
.Select (h => new {h.ComponentModel.Name, h.ComponentModel.Services})
.Dump();
}
void BuildContainer ()
{
container = new WindsorContainer ();
container.Register (
Classes
.FromThisAssembly ()
.BasedOn (typeof (IHandleMessages<>))
.OrBasedOn (typeof (ISubscribeTo<>))
.WithServiceBase ()
.LifestyleTransient ());
}
void Subscribe (IBus bus, IKernel kernel)
{
var baseType = typeof (ISubscribeTo<>);
var subscribers = kernel.GetAssignableHandlers (typeof (ISubscribeTo));
var eventTypes = subscribers
.SelectMany (handler => handler.ComponentModel.Services)
.Where (service => service.IsGenericType && service.GetGenericTypeDefinition () == baseType)
.Select (service => service.GetGenericArguments () [0])
.Distinct ();
var subscribeMethod = GetSubscribeMethod ();
foreach (var t in eventTypes) {
subscribeMethod.MakeGenericMethod (t).Invoke (bus, null);
}
}
MethodInfo GetSubscribeMethod ()
{
return typeof (IBus)
.GetMethods (BindingFlags.Instance | BindingFlags.Public)
.Where (m =>
string.Equals ("Subscribe", m.Name, StringComparison.OrdinalIgnoreCase) &&
m.IsGenericMethod && m.GetGenericArguments ().Length == 1 &&
m.GetParameters ().Length == 0)
.Single ();
}
public interface IBus
{
void Subscribe<T> ();
void Subscribe ();
}
public class RebusBus : IBus
{
public List<Type> subscribed = new List<Type> ();
public void Subscribe () {}
public void Subscribe<T> ()
{
subscribed.Add (typeof (T));
}
}
public interface IHandleMessages {}
public interface IHandleMessages<T> : IHandleMessages {}
public interface ISubscribeTo {}
public interface ISubscribeTo<T> : ISubscribeTo, IHandleMessages<T> {}
public class E1 {}
public class E2 {}
public class E3 {}
public class H1 : ISubscribeTo<E1> {}
public class H2 : ISubscribeTo<E2>, ISubscribeTo<E3> {}
public class H3 : ISubscribeTo<E1> {}
public class H4 : IHandleMessages<E1> {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment