AspectCore是适用于Asp.Net Core 平台的轻量级Aop(Aspect-oriented programming)解决方案,它更好的遵循Asp.Net Core的模块化开发理念,使用AspectCore可以更容易构建低耦合、易扩展的Web应用程序。

在使用过程中,由于相关文档、博客还未更新到.Net Core 3.0,本文操作参考了使用.Net Core 3.0的EasyCaching,并对其中公用的方法进行封装简化。

安装Aspectcore

此处配合微软自家的DI实现,安装Nuget包AspectCore.Extensions.DependencyInjection,其中包含AspectCore.Core和Microsoft.Extensions.DependencyInjection两个依赖。

Install-Package AspectCore.Extensions.DependencyInjection -Version 1.3.0

拦截器

  • 特性拦截器

    新建一个特性拦截器TestInterceptorAttribute,继承AbstractInterceptorAttribute,并重写Invoke方法,在方法中实现拦截相关业务。
public class TestInterceptorAttribute : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
return context.Invoke(next);
}
}
  • 全局拦截器

    新建一个全局拦截器TestInterceptor,继承AbstractInterceptor,并重写Invoke方法,在方法中实现拦截相关业务。
public class TestInterceptor : AbstractInterceptor
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
return context.Invoke(next);
}
}

注册服务

以下注册方式仅适用于asp.net core 3.0(目前只到3.0),已知在2.2版本中,需要在ConfigureServices方法中返回IServiceProvider,并且program.cs中也不再需要替换ServiceProviderFactory。

1.创建AspectCoreEctensions.cs扩展IServiceCollection

public static class AspectCoreExtensions
{
public static void ConfigAspectCore(this IServiceCollection services)
{
services.ConfigureDynamicProxy(config =>
{
//TestInterceptor拦截器类
//拦截代理所有Service结尾的类
config.Interceptors.AddTyped<TestInterceptor>(Predicates.ForService("*Service"));
});
services.BuildAspectInjectorProvider();
}
}

2.在Startup.cs中注册服务

public void ConfigureServices(IServiceCollection services)
{
services.ConfigAspectCore();
}

3.在Program.cs中替换ServiceProviderFactory

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseServiceProviderFactory(new AspectCoreServiceProviderFactory());

被拦截方法编写

  • 代理接口:在接口上标注Attribute
public interface ITestService
{
[TestInterceptor]
void Test();
}
  • 代理类(方法):在方法上标注Attribute,并且标注virtual
public class TestService
{
[TestInterceptor]
public virtual void Test()
{
//业务代码
}
}

拦截器业务编写

  • 执行被拦截方法
private async Task<object> RunAndGetReturn()
{
await Context.Invoke(Next);
return Context.IsAsync()
? await Context.UnwrapAsyncReturnValue()
: Context.ReturnValue;
}
  • 拦截器中的依赖注入
[FromContainer]
private RedisClient RedisClient { get; set; }
  • 获取被拦截方法的Attribute
private static readonly ConcurrentDictionary<MethodInfo, object[]>
MethodAttributes = new ConcurrentDictionary<MethodInfo, object[]>(); public static T GetAttribute<T>(this AspectContext context) where T : Attribute
{
MethodInfo method = context.ServiceMethod;
var attributes = MethodAttributes.GetOrAdd(method, method.GetCustomAttributes(true));
var attribute = attributes.FirstOrDefault(x => typeof(T).IsAssignableFrom(x.GetType()));
if (attribute is T)
{
return (T)attribute;
}
return null;
}
  • 获取被拦截方法返回值类型
public static Type GetReturnType(this AspectContext context)
{
return context.IsAsync()
? context.ServiceMethod.ReturnType.GetGenericArguments()First()
: context.ServiceMethod.ReturnType;
}
  • 处理拦截器返回结果
private static readonly ConcurrentDictionary<Type, MethodInfo>
TypeofTaskResultMethod = new ConcurrentDictionary<Type, MethodInfo>();
public object ResultFactory(this AspectContext context,object result)
{
var returnType = context.GetReturnType(); //异步方法返回Task<T>类型结果
if (context.IsAsync())
{
return TypeofTaskResultMethod
.GetOrAdd(returnType, t => typeof(Task)
.GetMethods()
.First(p => p.Name == "FromResult" && p.ContainsGenericParameters)
.MakeGenericMethod(returnType))
.Invoke(null, new object[] { result });
}
else
{
return result;
}
}

相关链接

ASP.NET Core 3.0 使用AspectCore-Framework实现AOP的更多相关文章

  1. ASP.NET Core 1.0: Using Entity Framework Core

    伴随着ASP.NET Core 1.0发布的还有Entity Framework Core 1.0; 官方文档链接:https://docs.efproject.net/en/latest/platf ...

  2. 打造静态分析器(二)基于Asp.Net Core 3.0的AspectCore组件检测

    上一篇,我们打造了一个简单的分析器,但是我们实际使用分析器就是为了对项目做分析检测,增加一些非语法的自检的 比如Asp.Net Core 3.0的替换依赖注入检测 设计分析 我们创建一个默认的Asp. ...

  3. [转]ASP.NET Core 1.0: Using Entity Framework Core 1.0 - Transaction

    本文转自:http://blog.csdn.net/alvachien/article/details/51576961 跟Entity Framework之前的版本不同,Class DbContex ...

  4. ASP.NET Core 1.0: Using Entity Framework Core 1.0 - Transaction

    跟Entity Framework之前的版本不同,Class DbContext不再有AcceptAllChanges()方法. 使用Transaction需要使用DbContext中的Databas ...

  5. ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0

    ASP.NET 5.0 将改名为 ASP.NET Core 1.0 ASP.NET MVC 6  将改名为 ASP.NET MVC Core 1.0 Entity Framework 7.0    将 ...

  6. [转帖]2016年时的新闻:ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0

    ASP.NET Core 1.0.ASP.NET MVC Core 1.0和Entity Framework Core 1.0 http://www.cnblogs.com/webapi/p/5673 ...

  7. .NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布

    众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL)系统上的一流开发平台选项.这个团队已经一起工作好几个月了,RHEL对.NET有许多需求.今天在 ...

  8. .NET Core & ASP.NET Core 1.0

    .NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布 众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL) ...

  9. .NET Core 1.0、ASP.NET Core 1.0和EF Core 1.0简介

    .NET Core 1.0.ASP.NET Core 1.0和EF Core 1.0简介 英文原文:Reintroducing .NET Core 1.0, ASP.NET Core 1.0, and ...

  10. [争什么! 掺在一起做撒尿牛丸啊! 笨蛋]ASP.NET Core 2.0 + EF6 + Linux +MySql混搭

    好消息!特好消息!同时使用ASP.NET Core 2.0和.NET Framework类库还能运行在linux上的方法来啦! 是的,你没有看错!ASP.NET Core 2.0,.NET Frame ...

随机推荐

  1. CAD打印图纸要怎么操作?简单方法分享给你

    大家日常生活中多多少少的都接触到过CAD文件,CAD图是借助CAD制图软件来进行绘制完成的.唯一的困惑就是CAD图纸的格式大多数均为dwg格式的,查看起来不是那么的方便?所以很多设计师们都会选择将图纸 ...

  2. mssql sqlserver 使用sql脚本剔除数据中的tab、空格、回车等特殊字符的方法分享

    摘要: 在sqlserver开发中,常常有同事反馈无法剔除空格,我们可以通过仔细检查发现,并不是空格字符,而是tab键,如下所示: 解决方法: 对于这些特殊字符的替换,我们需采用字符所对应的ascii ...

  3. vue+hammer.js完美实现长按、左滑,右滑等触控事件

    移动端使用手指直接操作的方式大受用户欢迎,这其中就包括了单点.多点.长按.双击等方式. 这么多触控事件,如果开发者自己实现,会浪费大量的时间和精力,快来看看 hammer.js 让我们轻松了多少吧. ...

  4. emacs 矩形操作

    emacs 矩形操作 如果使用图形化(GUI)的eamcs,使用M-x cua-mode,很好用,但是如果不是图形化的emacs(emacs -nw)的话,矩形操作就不能使用cua-mode. 非图形 ...

  5. Pwn-TestYourMemory

    题目地址 https://dn.jarvisoj.com/challengefiles/memory.838286edf4b832fd482d58ff1c217561 32位的程序,有NX保护,拖到I ...

  6. python工具-将视频按帧截取图片(附代码)

    描述:将一个视频流按帧数截取大量的图片 用途:AI的数据集制作,得到大量的图片,之后将其打标签 更改的地方 1.default--间隔的帧数   2.input/output--输入视频的路径.存放截 ...

  7. celery 异步发送短信验证码、延迟任务

    短信 celery.py import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffy ...

  8. 更换github账号后,push被旧账号阻止

    和网上多数的教程不同,我是需要直接更换账号.切换后push一直被阻止.解决后记录下办法 remote: Permission to new-name/practice.git denied to ol ...

  9. 记录错误or日记(更新中)

    前言: 从2018.8-17开始记录 本篇随笔记录做题时的小错误(大多数),考试总结(懒得总结了),做过的每个题的错误 2019.12.7 傻逼学校,给我三个小时假期给你们做题挣工资 2019.11. ...

  10. Paper | A novel deep learning-based method of improving coding efficiency from the decoder-end for HEVC

    目录 精彩叙述 细节 发表在2017年DCC. 这篇文章立意很简单,方法也很简单,但是做得早.效果好.引用量也不错(40+). 指标:在HEVC的intra.LDP.LDB和RA模式下,BDBR平均可 ...