gpt4 book ai didi

StructureMap 和装饰器模式

转载 作者:行者123 更新时间:2023-12-03 21:42:12 26 4
gpt4 key购买 nike

我正在使用 StructureMap,v. 2.5.3,并且在将接口(interface)上的实现链接在一起以实现装饰器模式时遇到了麻烦。

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

这是默认的非修饰版本,可以正常工作:

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

这是装饰器上的 ctor,我想调用它:
public CommentAuditService( ICommentService commentService, 
IAuditService auditService )

这有效,但不允许我访问装饰对象:
registry.ForRequestedType<ICommentService>()
.TheDefault.Is.OfConcreteType<CommentService>()
.EnrichWith(x => new CommentAuditService());

这把我带入了一个inf。环形:
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,我现在非常接近)

最佳答案

你非常亲近。尝试:

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

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

关于StructureMap 和装饰器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1443464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com