I believe Jimmy Bogard has a similar technique (IHandler) 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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 );
}
}
So it finds all the ISubscribe interfaces the target implements and then subscribes the target to the event T in the event aggregator.
1
2
3
4
public interface ISubscribe < E >
{
void Subscribe ( E e );
}
A simple example of usage:
1
2
3
4
5
6
7
8
public class SecurityController : IController ,
ISubscribe < RequestUserLoginEvent >
{
public void Subscribe ( RequestUserLoginEvent e )
{
Publish . Event (). ShowModal < IRequestUserLoginViewModel >();
}
}