gpt4 book ai didi

c# - AOP拦截属性

转载 作者:行者123 更新时间:2023-11-30 12:37:07 25 4
gpt4 key购买 nike

所以,我有这个问题,似乎没有人能够提供帮助。因此,我不会继续抨击,而是要把它扔出去寻找其他方法来给这只猫剥皮。

我目前有以下内容:

public interface ICustomerService
{
Customer GetCustomer(int id);
}

public class CustomerService : ICustomerService
{
public Customer GetCustomer(int id)
{
...
}
}

...使用 Unity 我有 IOC 设置,同时配置拦截,如:

IUnityContainer ioc = new UnityContainer();
ioc.RegisterType<ICustomerService, CustomerService>()
.Configure<Interception>()
.SetInterceptorFor<ICustomerService>(new InterfaceInterceptor());

我想要实现的是能够像这样在界面中放置属性:

public interface ICustomerService
{
[Log]
Customer GetCustomer(int id);
}

...定义如下:

public class LogAttribute: HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LogHandler();
}
}

...然后在 LogHandler 类中执行我想要的所有日志记录:

public class LogHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
... log stuff
}
}

我想要实现的是一个跟踪/日志系统,其中处理程序记录正在调用的 namespace.class.methodname,以及调用它的父 namespace.class.methodname。我尝试使用“输入”IMethodInvocation 参数来获取我想要的信息,但没有成功,问题是,输入返回“ICustomerService”接口(interface),同时检查父级的堆栈框架返回父级的实现类(例如. CustomerService) 意味着当我尝试使用 namespace.class.methodname 作为实体 ID 创建树结构时,ID 和 parentID 不匹配。

将参数放入 [Log] 属性中也不会起作用,因为我可以在其中放什么?如果我输入接口(interface)名称,我仍然会遇到与上面相同的问题,其中一个的 ID 是一个接口(interface)而父级是实现类。而且,我不能将实现类名放在接口(interface)的属性中,因为这首先违背了拥有接口(interface)的目的!

所以,这就是困境。有人有新想法吗?

最佳答案

我最终使用 PostSharp 来完全像这样实现日志记录。 http://www.postsharp.org

关于c# - AOP拦截属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826702/

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