2013-01-03 314 views
3

我一直在這方面有點麻煩。NServiceBus依賴注入

AndreasÖhlund回答了一個關於它的問題here,但是我一直無法使用他給出的建議讓它工作。

這裏是我的設置:

public abstract class CommandHandler<T> : IHandleMessages<T>, IDomainReadRepository where T : Command 
{ 
    public IDomainRepository DomainRepository { get; set; } 

    protected abstract void OnProcess(T command); 

    public TAggregate GetById<TAggregate>(Guid id) where TAggregate : IEventProvider, new() 
    { 
     return DomainRepository.GetById<TAggregate>(id); 
    } 

    public void Handle(T message) 
    { 
     OnProcess(message); 
     // Domain repository will save. 
    } 
} 

的想法是特定命令處理程序重寫OnProcess方法和做他們的事,那麼DomainRepository將節省一切。

下面是我註冊的組件:

public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization 
{ 
    public void Init() 
    { 
     Configure.With().DefiningCommandsAs(c => c.Namespace != null && c.Namespace.EndsWith("Commands")); 
     Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<DomainRepository>(DependencyLifecycle.InstancePerCall); 
     Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<EventStore.Sql.EventStore>(DependencyLifecycle.InstancePerCall); 
     Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<MongoDbObjectSecurityDescriptorRepository>(DependencyLifecycle.InstancePerCall); 
     Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<LocalTenantConfig>(DependencyLifecycle.InstancePerCall); 
    } 
} 

這些都是下降了由DomainRepository使用的鏈中的所有對象;但是,當我收到命令時,DomainRepository爲空。如果我註釋掉註冊DomainRepository需要的對象的行,我實際上會得到一個錯誤,說它無法創建它(Autofac DependencyResolutionException)。

應該注意的是,所有其他對象都使用構造函數注入(它們來自先前存在的項目)。我試圖改變他們使用公共財產注入,但它沒有任何區別。

如果有人能指出我在這裏做錯了,我們將不勝感激!

回答

7

將init方法中的代碼移動到實現INeedInitialization的不同類中。在那裏,使用Configure.Instance而不是Configure.With(),而不是Configure.Instance.DefaultBuilder()。

+0

非常棒 - 完成了這個訣竅!謝謝! – jacderida