C# 有没有办法在不使用属性分解的情况下将AOP应用于.NET库?
我完全理解我的问题是一个奇怪的问题,可能有很多更好的方法来实现我的目标,所以任何帮助都将不胜感激 其基本思想是跟踪在运行时对某些类型实体的某些属性所做的所有更改,而无需修改它们的代码 假设我有一个名为Foo的实体,如下所述:C# 有没有办法在不使用属性分解的情况下将AOP应用于.NET库?,c#,.net,aop,event-sourcing,C#,.net,Aop,Event Sourcing,我完全理解我的问题是一个奇怪的问题,可能有很多更好的方法来实现我的目标,所以任何帮助都将不胜感激 其基本思想是跟踪在运行时对某些类型实体的某些属性所做的所有更改,而无需修改它们的代码 假设我有一个名为Foo的实体,如下所述: class Foo { private string _bar; public string Bar { get { return _bar; } set { // so
class Foo
{
private string _bar;
public string Bar
{
get { return _bar; }
set
{
// some logic here...
_bar = value;
// some logic here...
}
}
}
基本上,我想要一个库,它允许我编写如下所示的代码:
Hook.For<Foo>()
.OnSet(foo => foo.Bar)
.Action((foo, value) =>
{
// save the state of the foo instance along with the value passed to the setter
});
Hook.For()
.start(foo=>foo.Bar)
.Action((foo,value)=>
{
//保存foo实例的状态以及传递给setter的值
});
我知道所需的功能包括添加一些额外的构建步骤来修改输出程序集IL代码。语法不需要如此流畅,我甚至不介意JSON或XML配置。其主要思想是不要更改应用程序中大量糟糕的遗留代码,而是使用外部监控(用于调试目的)
是否有任何AOP框架可以全局应用这样的方面,而不需要我用属性修饰每个属性或类?看起来PostSharp提供了在现有代码上应用外部方面的能力,如以下文章所述:
我现在就用这个解决方案。您可能还想看看GitHub上的Tyler Brinks项目: 该框架位于任意数量的IoC容器之上,用于在类之上注入AOP代理:
// Configure SNAP to look at all assemblies starting with the "ConsoleApplication1" namespace.
// Next, tell SNAP to intercept any code decorated with a DemoLoggingAttribute by running
// an instance of the DemoLoggingInterceptor class.
SnapConfiguration.For<StructureMapAspectContainer>(c =>
{
// Tell SNAP to only be concerned with stuff starting with this namespace.
c.IncludeNamespace("ConsoleApplication1*");
// Tell SNAP to intercept any method or class decorated with "DemoLoggingAttribute"
// by wrapping execution in your own DemoInterceptor class.
c.Bind<DemoLoggingInterceptor>().To<DemoLoggingAttribute>();
});
// Configure StructureMap as usual.
ObjectFactory.Configure(c => c.For<ISampleClass>().Use<SampleClass>());
// Use your own class to handle interception. Logging is a good example.
public class DemoLoggingInterceptor : MethodInterceptor
{
public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
{
// Log something important here.
// Then continue executing your method.
invocation.Proceed();
}
}
//配置SNAP以查看以“ConsoleApplication1”命名空间开头的所有程序集。
//接下来,让SNAP通过运行
//DemoLoggingInterceptor类的实例。
SnapConfiguration.For(c=>
{
//告诉SNAP只关心从这个名称空间开始的东西。
c、 IncludeNamespace(“控制台应用程序1*”);
//告诉SNAP截取任何用“DemoLoggingAttribute”修饰的方法或类
//通过在您自己的DemoInterceptor类中包装执行。
c、 绑定()到();
});
//像往常一样配置StructureMap。
Configure(c=>c.For().Use());
//使用您自己的类来处理拦截。日志记录就是一个很好的例子。
公共类DemoLoggingInterceptor:MethodInterceptor
{
公共重写void InterceptMethod(IInvocation调用、MethodBase方法、属性)
{
//在这里记录一些重要的事情。
//然后继续执行您的方法。
invocation.procedure();
}
}
SNAP需要属性,不能像PostSharp那样全局应用,而这正是OP所要求的。不管它是开源的,它是一个很好的简单工具,实现一个全局拦截器应该不会太难。