StructureMap 和装饰器模式 [英] StructureMap and the decorator pattern

查看:28
本文介绍了StructureMap 和装饰器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 StructureMap,v. 2.5.3,并且在将接口上的实现链接在一起以实现装饰器模式时遇到问题.

I'm using StructureMap, v. 2.5.3 and am having trouble with chaining together implementations on an interface to implement the Decorator pattern.

我习惯了 Windsor,在那里可以命名接口实现的变体并发送命名的 impl.进入另一个(默认)impl.

I'm used to Windsor, where it is possible to name variations on interface implementations and send the named impl. into another (default) impl.

这是默认的非装饰版本,效果很好:

This is the default, non decorated version, which works fine:

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

这是装饰器上的构造函数,我想调用它:

This is the ctor on the decorator, that I want to call:

public CommentAuditService( ICommentService commentService, 
                            IAuditService auditService )

这有效,但不能让我访问装饰对象:

This works, but does not give me access to the decorated object:

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

这需要我输入一个信息.循环:

This takes me int an inf. loop:

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

到目前为止,这在我看来应该起作用:

So far this is what seems to me should work:

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

然而,它将它发送到创建新的 CommentAuditService 实例的无限循环中

However it send it into an endless loop of creating new instances of CommentAuditService

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

Does anyone have an quick answer? (other than switching to Castle.Windsor, which I'm very close to at the moment)

推荐答案

你们非常接近.试试:

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

如果 AuditService 本身可能有依赖项,您会这样做:

If AuditService might itself have dependencies, you would do:

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

或者,如果您将最后一部分更改为:

Or, if you change the last part to:

ioc.GetInstance<IAuditService>()

您可以单独注册审计服务的具体类型.

you can register the concrete type of your audit service separately.

这篇关于StructureMap 和装饰器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆