2009-09-18 87 views
14

我正在使用StructureMap,v。2.5.3,並且在實現裝飾器模式的接口上將實現鏈接在一起時遇到問題。StructureMap和裝飾器模式

我已經習慣了Windsor,它可以在接口實現上命名變體併發送命名的impl。轉換爲另一個(默認)impl。

這是默認的,無裝飾的版本,它工作得很好:

ObjectFactory.Initialize(registry => 
{ 
    registry.ForRequestedType<ICommentService() 
    .TheDefault.Is.OfConcreteType<CommentService>(); 
... } 

這是裝飾的構造函數,我想打電話:

public CommentAuditService(ICommentService commentService, 
          IAuditService auditService) 

這工作,但確實不給我訪問裝飾對象:

registry.ForRequestedType<ICommentService>() 
    .TheDefault.Is.OfConcreteType<CommentService>() 
    .EnrichWith(x => new CommentAuditService()); 

這需要我int int。循環:

registry.ForRequestedType<ICommentService>() 
    .TheDefault.Is.OfConcreteType<CommentService>() 
    .EnrichWith(x => new CommentAuditService(new CommentService(), 
              new AuditService())); 

到目前爲止,這是在我看來,應該工作:

registry.ForRequestedType<ICommentService.() 
    .TheDefault.Is.OfConcreteType<CommentAuditService>() 
    .WithCtorArg("commentService") 
    .EqualTo(new CommentService()); 

然而,它發送到創建CommentAuditService

的新實例的無限循環

沒有人有快速回答? (除了切換到Castle.Windsor,我目前非常接近)

回答

21

你非常接近。嘗試:

registry.ForRequestedType<ICommentService>() 
    .TheDefaultIsConcreteType<CommentService>() 
    .EnrichWith(original => new CommentAuditService(original, 
             new AuditService())); 

如果AuditService本身可能有依賴性,你會怎麼做:

registry.ForRequestedType<ICommentService>() 
    .TheDefaultIsConcreteType<CommentService>() 
    .EnrichWith((ioc, original) => new CommentAuditService(original, 
            ioc.GetInstance<AuditService>())); 

或者,如果你改變了最後一部分:

ioc.GetInstance<IAuditService>() 

可以註冊具體類型您的審計服務分開。

+0

這就是機票!感謝Joshua – iammaz 2009-09-21 07:30:52