gpt4 book ai didi

structuremap - 拦截方法调用以增加功能的最简单方法是什么?

转载 作者:行者123 更新时间:2023-12-04 05:19:37 24 4
gpt4 key购买 nike

假设我有一个返回 Post 列表的存储库s。存储库接口(interface)有一个 GetAll()做它所建议的方法。

现在根据我不应该将域逻辑放入存储库的理论,我想拦截对具体 GetAll() 的调用方法,以便我可以将以下逻辑添加到 GetAll()结果:

return GetAll().OrderByDescending(p => p.Posted).ToList();

我想拦截它的原因是因为(1)我不想让客户端记住调用扩展方法( OrderByDescending 或一些无用的包装器),我希望每次都调用它并且(2)我不想让我所有的具体实现都记得订购 GetAll()结果 - 我希望这个逻辑在任何存储库外部的一个地方。

最简单的方法是什么?

我已经在使用 StructureMap所以如果我能用这个拦截它可能是一个低成本的选择。但我不认为 SM 拦截方法调用,只是对象实例的创建?

我需要去 proxy or mixin图案?我需要全押CaSTLe Dynamic Proxy ?或者有没有 another method我应该考虑还是组合?

我对我上面的特定示例的具体建议非常感兴趣。我是 AOP 的新手,所以请温柔一点。

最佳答案

DynamicProxy选项。它比我想象的更容易使用。

只需要using Castle.DynamicProxy;引用...

一点IInterceptor ...

public class PostRepoInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();

if (invocation.Method.Name.Equals("GetAll", StringComparison.InvariantCultureIgnoreCase))
invocation.ReturnValue = this.GetModifiedGetAllResult(invocation.ReturnValue);
}

private object GetModifiedGetAllResult(object getAllResult)
{
return Post.GetOrderedPosts((IList<Post>)getAllResult);
}
}

StructureMap 配置中的两个新行:
    public RepoRegistry()
{
var pg = new ProxyGenerator();

For<IPostRepository>()
.EnrichAllWith(z => pg.CreateInterfaceProxyWithTarget<IPostRepository>(z, new PostRepoInterceptor()));
}

..它完成了。 GetAll()现在表现出我想要的样子。我仍然可以以我熟悉的方式使用这些接口(interface),并且我已经将其保持为 DRY 并为 DDD 解耦。

感谢 SamAndre .

关于structuremap - 拦截方法调用以增加功能的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496985/

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