Using structuremap to Register Generic Types
I am new to structuremap. I am trying to get Structuremap to auto-register
public void RegisterAllEventHandlers()
{
Scan(cfg =>
{
cfg.TheCallingAssembly();
//cfg.IncludeNamespaceContainingType<NewCustomerCreated>();
cfg.IncludeNamespace("ParentNameSpace");
cfg.AddAllTypesOf(typeof (IHandle<NewCustomerCreated>));
});
//For(typeof (IHandle<>)).Use(typeof (NewCustomerCreated));
}
NewCustomerCreated
is the event and I want to register all Handlers for this event ie ones using IHandle<NewCustomerCreated>
The following code is working but I am sure there it can be done by scanning :-
ObjectFactory.Initialize(x =>
{
x.For(typeof(IHandle<NewCustomerCreated>))
.Add(new NewCustomerCreatedHandler());
x.For(typeof(IHandle<NewCustomerCreated>))
.Add(new SendWelcomeEmailToNewCustomer());
});
I am trying to use DomainEvent raiser from http://blog.robustsoftware.co.uk/2009/08/better-domain-event-raiser.html
** I would appreciate if someone can edit the question to reflect what I am asking in a better way **
Thank you,
Mar
Edit 1: Adding Code from blog
public interface IEventDispatcher
{
void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent;
}
public static class DomainEventDispatcher
{
public static IEventDispatcher Dispatcher { get; set; }
public static void Raise<TEvent>(TEvent eventToRaise) where TEvent : IDomainEvent
{
Dispatcher.Dispatch(eventToRaise);
}
}
public class StructureMapEventDispatcher : IEventDispatcher
{
public void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent
{
foreach (var handler in ObjectFactory.GetAllInstances<IHandle<TEvent>>())
{
handler.Handle(eventToDispatch);
}
}
From my test project I am calling registry class which will scan the assembly
public void RegisterAllEventHandlers()
{
Scan(cfg =>
{
cfg.TheCallingAssembly();
cfg.IncludeNamespace("Project1");
//cfg.AddAllTypesOf(typeof(IHandle<NewCustomerCreated>));
cfg.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
});
// This initializes correctly
//ObjectFactory.Initialize(x =>
//{
// x.For(typeof(IHandle<NewCustomerCreated>))开发者_开发问答.Add(new NewCustomerCreatedHandler());
//});
// Handler returns 0 count
var handler =ObjectFactory.GetAllInstances<IHandle<NewCustomerCreated>>();
}
and then
var eventDispatcher = new StructureMapEventDispatcher();
DomainEventDispatcher.Dispatcher = eventDispatcher;
Try this:
cfg.AddAllTypesOf(typeof (IHandle<>));
Then your container will do the rest:
var handler = container.GetInstance<IHandler<NewCustomerCreated>>();
If you need more control take a look at this: https://stackoverflow.com/questions/516892/structuremap-auto-registration-for-generic-types-using-scan
精彩评论