2009-09-18 92 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