2010-10-24 45 views
2

我是新來的結構映射。我試圖讓Structuremap自動註冊使用結構映射來註冊泛型

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是事件,我想用IHandle<NewCustomerCreated>

下面的代碼正在註冊即那些所有的處理程序爲這個事件,但我相信有它可以通過掃描來完成: -

ObjectFactory.Initialize(x => 
    {              
     x.For(typeof(IHandle<NewCustomerCreated>)) 
      .Add(new NewCustomerCreatedHandler());                   
     x.For(typeof(IHandle<NewCustomerCreated>)) 
      .Add(new SendWelcomeEmailToNewCustomer()); 
    }); 

我想使用DomainEvent專業戶從 http://blog.robustsoftware.co.uk/2009/08/better-domain-event-raiser.html

**

我將不勝感激,如果有人可以編輯的問題,以反映我要求以更好的方式**

謝謝

編輯1:從博客

添加代碼
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); 

      } 

     } 

從我的測試項目,我呼籲登記類,它會掃描裝配

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>>(); 





     } 

然後

var eventDispatcher = new StructureMapEventDispatcher(); 
      DomainEventDispatcher.Dispatcher = eventDispatcher; 

回答

2

試試這個:

cfg.AddAllTypesOf(typeof (IHandle<>)); 

然後你的容器會完成剩下的:

var handler = container.GetInstance<IHandler<NewCustomerCreated>>(); 

如果您需要更多的控制來看看這個: https://stackoverflow.com/questions/516892/structuremap-auto-registration-for-generic-types-using-scan

+0

處理程序仍然返回空。有什麼方法可以在調用AddAllTypesOf時查找添加到容器的所有實例嗎? – TheMar 2010-10-24 04:27:31

+1

我想我錯了。我必須做ObjectFactory.Initialize(init => {init.AddRegistry ();});然後開始工作。非常感謝 – TheMar 2010-10-24 05:13:59

+0

作爲一個結構圖新手我想確保添加上面的代碼是正確的過程,而不僅僅是一些破解它的工作。謝謝 – TheMar 2010-10-24 13:48:32