如果你创造你的方法中有很多重复的代码就可以考虑用aop来精简代码了。比如说你想监控每个方法的耗时,按照传统的方法是每个方法都加上监控代码,如果用AOP思想去办理问题,就可以把跟监控代码放到方法的表面去写。
AOP思想的运用处景:
AOP切面有点像拦截器,不过跟拦截器有点差异。

这个例子开拓环境利用的是.Net Core 3.0,用的AOP框架是Autofac,通过Nuget安装Autofac.Extras.DynamicProxy组件。
利用步骤
1.Startup中把BlogCacheAOP切面 切入到Titan.Blog.AppService.dll下所有接口实现里。
var servicesDllFile = Path.Combine(basePath, \"大众Titan.Blog.AppService.dll\"大众);//获取项目绝对路径
var assemblysServices = Assembly.LoadFile(servicesDllFile);
builder.RegisterAssemblyTypes(assemblysServices)
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(BlogCacheAOP));//AOP切面缓存
2.切面公共代码
3.给方法标记特性,只有指定特性的方法才会实行公共代码
/// <summary>
/// 获取系统中所有的权限
/// </summary>
/// <returns></returns>
[Caching(AbsoluteExpiration = 10)]
public async Task<List<SysRoleModuleButtonDto>> GeRoleModule()
{
var dto = await _iSysRoleModuleButtonRepository.QueryAsNoTracking(x => x.ModuleType == 0);//
var roleModuleButton = dto.MapToList<SysRoleModuleButton, SysRoleModuleButtonDto>();
if (roleModuleButton.Count > 0)
{
foreach (var item in roleModuleButton)
{
item.SysRole = _iSysRoleRepository.QueryBySql($\公众select from SysRole where SysRoleId='{item.SysRoleId}' and IsDelete!=1 and RoleStatus=1\"大众).Result.FirstOrDefault();
item.SysModule = _iSysModuleRepository.QueryBySql($\公众select from SysModule where SysModuleId='{item.SysModuleId}' and ModuleStatus=1 and IsDelete!=1\"大众).Result.FirstOrDefault();
}
}
return roleModuleButton;
}
这个是AOP切面缓存,它的功能是将包含CachingAttribute特性的方法的返回值缓存到Redis里,下次在访问这个方法,会先去缓存中查询如果有则直接跳过这个方法,直接从Redis里获取之前缓存的结果集,如果没有则会实行方法获取返回值在缓存到Redis里。
以此,我们可以开拓其他类似功能,比如性能监控,日志监控,AOP事务,是不是很强大。详细代码实行流程请下载这个项目(下面有github地址),自己调试下上面的例子就明白了。
还有一个要把稳的,我这个项目掌握器和做事实现解耦了,如果没有解耦的话,掌握器直接调做事的话,AOP注册办法和做事要做修正。
1.Startup中AOP注册代码
////标记了虚方法virtual的才会进入切面
var assemblysModels = Assembly.Load(\"大众Titan.Blog.AppService\"大众);
builder.RegisterAssemblyTypes(assemblysModels)
.EnableClassInterceptors()
.InterceptedBy(typeof(BlogCacheAOP));
2.方法要加上virtual,否则进不了切面
/// <summary>
/// 获取系统中所有的权限
/// </summary>
/// <returns></returns>
[Caching(AbsoluteExpiration = 10)]
public virtual async Task<List<SysRoleModuleButtonDto>> GeRoleModule()
{
var dto = await _iSysRoleModuleButtonRepository.QueryAsNoTracking(x => x.ModuleType == 0);//
var roleModuleButton = dto.MapToList<SysRoleModuleButton, SysRoleModuleButtonDto>();
if (roleModuleButton.Count > 0)
{
foreach (var item in roleModuleButton)
{
item.SysRole = _iSysRoleRepository.QueryBySql($\公众select from SysRole where SysRoleId='{item.SysRoleId}' and IsDelete!=1 and RoleStatus=1\公众).Result.FirstOrDefault();
item.SysModule = _iSysModuleRepository.QueryBySql($\"大众select from SysModule where SysModuleId='{item.SysModuleId}' and ModuleStatus=1 and IsDelete!=1\"大众).Result.FirstOrDefault();
}
}
return roleModuleButton;
}
3.切面代码不须要改动
五、结语AOP思想实际上便是想把业务和公共的处理分开,对原有的代码没有一点入侵。我以为学习一个新技能之前,先别读那么多观点性的东西,觉得越看越糊涂,只会对学习新技能产生恐怖和抵触生理。我们可以先看看新技能它能办理什么问题,运用处景是什么,这对学习新技能该当是有好处的。