I have some code which basically grabs an event Handler which handles multiple events each handle method on IHandles handles 1 event.
public interface IHandles { }
public interface IHandles<T> : IHandles
{
void Handle(T message);
}
public void SubscribeHandler(IHandles eventHandler)
{
var genericHandler = typeof(IHandles<>);
var supportedEventTypes = eventHandler.GetType()
.GetInterfaces()
.Where(iface => iface.IsGenericType && iface.GetGenericTypeDefinition() == genericHandler)
.Select(iface => iface.GetGenericArguments()[0])
.ToList();
// Register this handler for each of the handled types.
foreach (var eventType in supportedEventTypes)
{
Subscribe(eventType.GetType(),
Delegate.CreateDelegate(eventType, eventHandler, "Handle")
);
}
}
Now the first bit works but im not sure whether the Create Delegate part will work and if its the best way. Is it possible to create an Action ?
It may be better to get Subscribe to store IHandles instead of Delgate , but its nice to be able to just register disposable actions especially for unit testing.
public IDisposable Subscribe(Type t, Delegate delegate1)
{
var key = t;
if (!actions.ContainsKey(key))
actions.Add(key, new List<Delegate>());
actions[key].Add(delegate1);
return new DomainEventRegistrationRemover(delegate { actions[key].Remove(delegate1); });
}
Anyway i went with implementing the store as IDictionary and then create an IHandles from the Action ..