0%

简述AOP编程

aop是面向切面编程的简称,对业务逻辑中的各个部分切割隔离,使耦合度降到最低,不仅增加了开发效率,还增强了系统的重用性和可维护性。
个人理解是把面向对象编程和面向函数编程结合在了一起。

说了这多的好处,那么AOP如何实现呢

Autofac.Aop里面提供了方便的AOP实现方式 下面我用Autofac.Aop做了个小示例

1
2
3
4
5
6
7
public class TestOnMethodBondedAspect : OnMethodBondedAspect
{
public override void OnExecuting(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("Some things running");
}
}
1
2
3
4
5
public interface IPerson
{
[TestOnMethodBondedAspect]
string DoSomeThing(string name);
}
1
2
3
4
5
6
7
public class Studen : IPerson
{
public string DoSomeThing(string name)
{
return "I im" + name+ ", I'm studying";
}
}

下面我们把对象注入容器中 并且调用 IPerson的 DoSomeThing

1
2
3
4
5
6
7
8
var builder = new ContainerBuilder();
builder.RegisterType<Studen>().As<IPerson>()//;
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(MethodInterceptor));
builder.Register(x => new MethodInterceptor());
Container = builder.Build();
var studen= Container.Resolve<IPerson>();
Console.WriteLine(studen.DoSomeThing("Yahui"));

执行结果

Some things running
I im Yahui, I'm studying

如果熟悉asp.net mvc 的朋友会感觉aop很像其中的filter,的确很像 aop就是让各个业务之间实行拦截,业务更清晰,将耦合度降到最低

这里我用autofac作为DI工具因为autofac支持的.NET版本比较新,纯属个人爱好
Spring.net Castle.Windsor,Unity等也都有AOP的实现方式,感兴趣的朋友可以动手去试试,对比下其中的区别和优劣。