Aspect Oriented Programming(AOP)是较为热门的一个话题。AOP,国内我们都习惯称之为:面向切面编程

下面直接code 干货展示:(一般人我还不告诉,嘻嘻)

1:导入相关的包:AutoFac 默认最新稳定版即可
Autofac.Extensions.DependencyInjection Version="7.1.0" 
Autofac.Extras.DynamicProxy Version="6.0.0"

2:AutoFac注入的扩展方法

 1 using System;
2 using System.Linq;
3 namespace ZRF.CRM.Commoms
4 {
5 using Autofac;
6 using Autofac.Extras.DynamicProxy;
7 using Microsoft.AspNetCore.Mvc;
8 using System.Reflection;
9 using ZRF.CRM.Commoms.Interceptors;
10 using ZRF.CRM.MyAttrobutrs;
11
12 public static class ContainerBuilderExtenTion
13 {
14 public static void DependInjecterIoc(this ContainerBuilder builder)
15 {
16 builder.RegisterType<TransactionScopeAsyncInterCeptor>();
17 builder.RegisterAssemblyTypes(Assembly.Load("ZRF.CRM.Service"))
18 .AsImplementedInterfaces().PropertiesAutowired().InterceptedBy(typeof(TransactionScopeAsyncInterCeptor)).EnableInterfaceInterceptors().OnRegistered(t =>
19 {
20 Console.WriteLine("ZRF.CRM.Service===Register_ok");
21 });
22 }
23 }
24 }

3:新增ConfigureContainer(ContainerBuilder builder)方法,并在Startup方法中注册

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Reflection;
5 using System.Threading.Tasks;
7 using Autofac;
8 using Microsoft.AspNetCore.Builder;
9 using Microsoft.AspNetCore.Hosting;
10 using Microsoft.AspNetCore.Mvc;
11 using Microsoft.AspNetCore.Mvc.Controllers;
12 using Microsoft.Extensions.Configuration;
13 using Microsoft.Extensions.DependencyInjection;
14 using Microsoft.Extensions.DependencyInjection.Extensions;
15 using Microsoft.Extensions.Hosting;
16 using WebApplication1.IOCS;
17 using ZRF.CRM.Commoms;
18 namespace WebApplication1
19 {
20 public class Startup
21 {
22 public Startup(IConfiguration configuration)
23 {
24 Configuration = configuration;
25 }
26 public void ConfigureContainer(ContainerBuilder builder)
27 {
28 builder.DependInjecterIoc();
29
30 //控制器属性注入
31 builder.RegisterModule<ControllerModule>();
32 }
33 public IConfiguration Configuration { get; }
34
35 // This method gets called by the runtime. Use this method to add services to the container.
36 public void ConfigureServices(IServiceCollection services)
37 {
38 services.AddControllersWithViews();
39
40 //core 3.0级以上
41 services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
42 }
43
44 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
45 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
46 {
47 if (env.IsDevelopment())
48 {
49 app.UseDeveloperExceptionPage();
50 }
51 else
52 {
53 app.UseExceptionHandler("/Home/Error");
54 }
55 app.UseStaticFiles();
56
57 app.UseRouting();
58
59 app.UseAuthorization();
60
61 app.UseEndpoints(endpoints =>
62 {
63 endpoints.MapControllerRoute(
64 name: "default",
65 pattern: "{controller=Home}/{action=Index}/{id?}");
66 });
67 }
68 }
69 }

4:Controller

 1 using Microsoft.AspNetCore.Mvc;
2 using Microsoft.Extensions.Logging;
3 using System;
4 using System.Collections.Generic;
5 using System.Diagnostics;
6 using System.Linq;
7 using System.Threading.Tasks;
8 using WebApplication1.Models;
9 using ZRF.CRM.MyAttrobutrs;
10 using ZRF.CRM.InterFaces;
11 namespace WebApplication1.Controllers
12 {
13 [ControllerCanInjectPropertity]
14 public class HomeController : Controller
15 {
16 private readonly ILogger<HomeController> _logger;
17
18 IDoLog _dolog;
19 ITest002Service _service;
20 public IDoLog _dolog2 { get; set; }
21
22 public HomeController(ILogger<HomeController> logger, IDoLog dolog, ITest002Service service)
23 {
24 _logger = logger;
25 _dolog = dolog;
26 this._service = service;
27 }
28
29 public IActionResult Index()
30 {
31 var boolflag = _dolog2.LogWork("aaaa");
32 bool flag = _dolog.LogWork("qqai");
33 var getMsg = _service.Dowork("有aop的方法");
34 Console.WriteLine("Aop获取到方法:" + getMsg);
35 //_service.DoWork02("没有aop的普通方法");
36 return View();
37 }
38
39 public IActionResult Privacy()
40 {
41 return View();
42 }
43
44 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
45 public IActionResult Error()
46 {
47 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
48 }
49 }
50 }

5:InterFace 

 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace ZRF.CRM.InterFaces
6 {
7
8 public interface ITest002Service
9 {
10 string Dowork(string msg);
11 string DoWork02(string msg);
12 }
13 }

6:Service

 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 namespace ZRF.CRM.Service
5 {
6 using ZRF.CRM.InterFaces;
7 using ZRF.CRM.MyAttrobutrs;
8
9 public class Test002Service : ITest002Service
10 {
11 [TransactionScopeAsync]
12 public string Dowork(string msg)
13 {
14
15 return $"Test002Service:Dowork {DateTime.Now}-{msg}";
16 }
17
18 public string DoWork02(string msg)
19 {
20 return $"Test002Service:DoWork02:{DateTime.Now}-{msg}";
21 }
22 }
23 }

7:自定义特性,将来判断哪些方法可以aop

 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace ZRF.CRM.MyAttrobutrs
6 {
7 [AttributeUsage(AttributeTargets.Method)]
8 public class TransactionScopeAsyncAttribute : Attribute
9 {
10 }
11
12 }

8:自定义类来实现Aop的IInterceptor方法

 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace ZRF.CRM.Commoms.Interceptors
6 {
7 using Autofac;
8 using Castle.DynamicProxy;
9 using System.Reflection;
10 using System.Transactions;
11 using ZRF.CRM.MyAttrobutrs;
12
13 public class TransactionScopeAsyncInterCeptor : IInterceptor
14 {
15 public void Intercept(IInvocation invocation)
16 {
17
18 if (HaveAsyncTrascAttribute(invocation))
19 {
20 TransactionScope scope = null;
21 try
22 {
23 scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
24 Console.WriteLine("TransactionScopeAsyncFlowOption之前=======");
25 invocation.Proceed();
26 scope.Complete();
27 Console.WriteLine("invocation.Proceed()用户自己的逻辑处理ok=======");
28 Console.WriteLine("TransactionScopeAsyncFlowOption之后=======");
29 }
30 catch (Exception)
31 {
32 Console.WriteLine("TransactionScopeAsyncInterCeptor:发生异常");
33 if (scope != null)
34 {
35 scope.Dispose();
36 }
37 }
38 }
39 else {
40 Console.WriteLine("没有异步事务发生!");
41 invocation.Proceed();
42 return;
43 }
44 }
45
46 private bool HaveAsyncTrascAttribute(IInvocation invocation)
47 {
48 var methodInfo = invocation.MethodInvocationTarget ?? invocation.Method;
49 if (methodInfo.GetCustomAttribute<TransactionScopeAsyncAttribute>() != null)
50 {
51 return true;
52 }
53 else { return false; }
54 }
55 }
56 }

9:来一张测试的截图

10:最后欢迎留言指教

Asp.netCore 3.1控制器属性注入and异步事务Aop by AutoFac的更多相关文章

  1. ASP.NETCore 3.0 Autofac替换及控制器属性注入及全局容器使用

    1.Autofac基础使用 参考: https://www.cnblogs.com/li150dan/p/10071079.html 2.ASP.NETCore 3.0 Autofac 容器替换 需要 ...

  2. Spring.Web.Mvc 注入(控制器属性注入)

    1.web.config配置 <?xml version="1.0" encoding="utf-8"?><!-- 有关如何配置 ASP.NE ...

  3. asp.netcore di 实现批量接口注入

    废话少说,先上代码 public static Dictionary<Type, Type[]> GetImpleAndInterfaces(string assemblyName,str ...

  4. 使用 autofac 实现 asp .net core 的属性注入

    使用 autofac 代替 asp .net core 默认的 IOC 容器,可实现属性注入. 之前的使用方式不受影响. 源码已开源: dotnet-campus/Autofac.Annotation ...

  5. 基于autofac的属性注入

    基于autofac的属性注入 什么是属性注入 在了解属性注入之前,要先了解一下DI(Dependency Injection),即依赖注入.在ASP.NET Core里自带了一个IOC容器,而且程序支 ...

  6. Asp.NETCore让FromServices回来

    起因 这两天,我忽然有点怀念 Asp.NET MVC 5 之前的时代,原因是我看到项目里面有这么一段代码(其实不止一段,几乎每个 Controller 都是) [Route("home&qu ...

  7. ASP.NET Core中使用IOC三部曲(二.采用Autofac来替换IOC容器,并实现属性注入)

    前言 本文主要是详解一下在ASP.NET Core中,自带的IOC容器相关的使用方式和注入类型的生命周期. 这里就不详细的赘述IOC是什么 以及DI是什么了.. emm..不懂的可以自行百度. 目录 ...

  8. 在netcore中实现字段和属性注入

    简单来说,使用Ioc模式需要两个步骤,第一是把服务注册到容器中,第二是从容器中获取服务,我们一个一个讨论并演化.这里不会考虑使用如Autofac等第三方的容器来代替默认容器,只是提供一些简单实用的小方 ...

  9. 007.ASP.NET MVC控制器依赖注入

    原文链接:http://www.codeproject.com/Articles/560798/ASP-NET-MVC-Controller-Dependency-Injection-for-Be 前 ...

随机推荐

  1. list转long[]数组

    //list转long数组List<Long> list = new ArrayList<>(); Long[] skuIds = list.toArray(new Long[ ...

  2. Redis主从复制getshell技巧

    Redis未授权漏洞常见的漏洞利用方式: Windows下,绝对路径写webshell .写入启动项. Linux下,绝对路径写webshell .公私钥认证获取root权限 .利用contrab计划 ...

  3. 第七章节 BJROBOT 选择区域自主构建地图【ROS全开源阿克曼转向智能网联无人驾驶车】

    1.把小车平放在地板上,用资料里的虚拟机,打开一个终端 ssh 过去主控端启动roslaunch znjrobot bringup.launch 2.在虚拟机端再打开一个终端,ssh 过去主控端启动r ...

  4. sql优化最佳实践

    1.选择最有效率的表连接顺序 首先要明白一点就是SQL 的语法顺序和执行顺序是不一致的 SQL的语法顺序: select   [distinct] ....from ....[xxx  join][o ...

  5. FTP服务器的搭建和使用(centos7)

    1.显示如下图则表示已安装vsftp软件 如过没有则可以通过yum源进行安装 yum install -y vsftpd 操作:service vsftpd start|stop|restart 2. ...

  6. ElasticSearch教程——filter与query对比(转学习使用)

    一.数据准备 PUT /company/employee/2 { "address": { "country": "china", &quo ...

  7. Scaled-YOLOv4 快速开始,训练自定义数据集

    代码: https://github.com/ikuokuo/start-scaled-yolov4 Scaled-YOLOv4 代码: https://github.com/WongKinYiu/S ...

  8. 杭电OJ----1097:一个难题(c++)

    问题描述 lcy给feng5166,lwg,JGShining和Ignatius带来了一个难题:给了a和b,如何知道a ^ b.每个人都反对这个BT问题,所以lcy使问题比开始容易. 这个难题描述了: ...

  9. Java基础--接口回调(接口 对象名 = new 类名)理解

    接口 对象名1 = new 类名和类名 对象名2 = new 类名的区别是什么? 实例 /** *Person.java 接口 */ public interface Person { void in ...

  10. JavaScript高级程序设计(第4版)知识点总结

    介绍 JavaScript高级程序设计 第四版,在第三版的基础上添加了ES6相关的内容.如let.const关键字,Fetch API.工作者线程.模块.Promise 等.适合具有一定编程经验的 W ...