I believe Jimmy Bogard has a similar technique (IHandler<T>) with ASP .Net MVC but I thought I would still share the convention I’ve been using to wire up subscriptions to the Prism Event Aggregator.
Whenever an object is built with StructureMap, it goes through all the TypeInterceptors. I have a SubscriptionTypeInterceptor:
public class SubscriptionInterceptor : TypeInterceptor
{
public object Process(object target, IContext context)
{
var eventAggregator = context.GetInstance<IEventAggregator>();
// Get interface ISubscribe<E>
var interfaces = target.GetType().GetInterfaces().Where(i => i.Name.Contains("ISubscribe"));
foreach (var type in interfaces)
{
// typeof(E)
var eventType = type.GetGenericArguments()[0];
var setupMethod = GetType().GetMethod("Setup");
setupMethod.MakeGenericMethod(eventType).Invoke(this, new[] { target, eventAggregator });
}
return target;
}
public bool MatchesType(Type type)
{
return type.ImplementsInterfaceTemplate(typeof(ISubscribe<>));
}
public void Setup<T>(ISubscribe<T> subscriber, IEventAggregator eventAggregator)
{
eventAggregator
.GetEvent<CompositePresentationEvent<T>>()
.Subscribe(subscriber.Subscribe);
}
}
{
public object Process(object target, IContext context)
{
var eventAggregator = context.GetInstance<IEventAggregator>();
// Get interface ISubscribe<E>
var interfaces = target.GetType().GetInterfaces().Where(i => i.Name.Contains("ISubscribe"));
foreach (var type in interfaces)
{
// typeof(E)
var eventType = type.GetGenericArguments()[0];
var setupMethod = GetType().GetMethod("Setup");
setupMethod.MakeGenericMethod(eventType).Invoke(this, new[] { target, eventAggregator });
}
return target;
}
public bool MatchesType(Type type)
{
return type.ImplementsInterfaceTemplate(typeof(ISubscribe<>));
}
public void Setup<T>(ISubscribe<T> subscriber, IEventAggregator eventAggregator)
{
eventAggregator
.GetEvent<CompositePresentationEvent<T>>()
.Subscribe(subscriber.Subscribe);
}
}
So it finds all the ISubscribe<T> interfaces the target implements and then subscribes the target to the event T in the event aggregator.
public interface ISubscribe<E>
{
void Subscribe(E e);
}
{
void Subscribe(E e);
}
A simple example of usage:
public class SecurityController : IController,
ISubscribe<RequestUserLoginEvent>
{
public void Subscribe(RequestUserLoginEvent e)
{
Publish.Event().ShowModal<IRequestUserLoginViewModel>();
}
}
ISubscribe<RequestUserLoginEvent>
{
public void Subscribe(RequestUserLoginEvent e)
{
Publish.Event().ShowModal<IRequestUserLoginViewModel>();
}
}
0 comments:
Post a Comment