Asp.netCore 3.1控制器属性注入and异步事务Aop by AutoFac
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的更多相关文章
- ASP.NETCore 3.0 Autofac替换及控制器属性注入及全局容器使用
1.Autofac基础使用 参考: https://www.cnblogs.com/li150dan/p/10071079.html 2.ASP.NETCore 3.0 Autofac 容器替换 需要 ...
- Spring.Web.Mvc 注入(控制器属性注入)
1.web.config配置 <?xml version="1.0" encoding="utf-8"?><!-- 有关如何配置 ASP.NE ...
- asp.netcore di 实现批量接口注入
废话少说,先上代码 public static Dictionary<Type, Type[]> GetImpleAndInterfaces(string assemblyName,str ...
- 使用 autofac 实现 asp .net core 的属性注入
使用 autofac 代替 asp .net core 默认的 IOC 容器,可实现属性注入. 之前的使用方式不受影响. 源码已开源: dotnet-campus/Autofac.Annotation ...
- 基于autofac的属性注入
基于autofac的属性注入 什么是属性注入 在了解属性注入之前,要先了解一下DI(Dependency Injection),即依赖注入.在ASP.NET Core里自带了一个IOC容器,而且程序支 ...
- Asp.NETCore让FromServices回来
起因 这两天,我忽然有点怀念 Asp.NET MVC 5 之前的时代,原因是我看到项目里面有这么一段代码(其实不止一段,几乎每个 Controller 都是) [Route("home&qu ...
- ASP.NET Core中使用IOC三部曲(二.采用Autofac来替换IOC容器,并实现属性注入)
前言 本文主要是详解一下在ASP.NET Core中,自带的IOC容器相关的使用方式和注入类型的生命周期. 这里就不详细的赘述IOC是什么 以及DI是什么了.. emm..不懂的可以自行百度. 目录 ...
- 在netcore中实现字段和属性注入
简单来说,使用Ioc模式需要两个步骤,第一是把服务注册到容器中,第二是从容器中获取服务,我们一个一个讨论并演化.这里不会考虑使用如Autofac等第三方的容器来代替默认容器,只是提供一些简单实用的小方 ...
- 007.ASP.NET MVC控制器依赖注入
原文链接:http://www.codeproject.com/Articles/560798/ASP-NET-MVC-Controller-Dependency-Injection-for-Be 前 ...
随机推荐
- 开发规范(二)如何写单元测试 By 阿里
- FSMC全称“静态存储器控制器”。
FSMC全称"静态存储器控制器". 使用FSMC控制器后,可以把FSMC提供的FSMC_A[25:0]作为地址线,而把FSMC提供的FSMC_D[15:0]作为数据总线. (1)当 ...
- 自动化运维工具-Ansible之1-基础
自动化运维工具-Ansible之1-基础 目录 自动化运维工具-Ansible之1-基础 Ansible 基本概述 定义 特点 架构 工作原理 任务执行模式 命令执行过程 Ansible 安装 Ans ...
- TurtleBot3使用课程-第二节a(北京智能佳)
目录 1.[第3类]LRF(LDS)传感器 2 1.1 传感器包安装 2 1.1.1 传感器端口访问设置 2 1.1.2 运行hlds_laser_publisher节点 2 1.1.3 在RViz中 ...
- Spark学习进度-Spark环境搭建&Spark shell
Spark环境搭建 下载包 所需Spark包:我选择的是2.2.0的对应Hadoop2.7版本的,下载地址:https://archive.apache.org/dist/spark/spark-2. ...
- Docker部署&MySQL部署
Docker部署 本文采用的是阿里云的centos7 # 更新yum yum update # 安装docker yum install docker # 启动docker systemctl sta ...
- instanceof和isInstance的区别
instanceof 是一个操作符(类似new, ==等) ( Object reference variable ) instanceof (class/interface type) if(a i ...
- rocketmq-cpp-client Visual Studio 2019 编译
rocketmq-cpp-client Visual Studio 2019 编译 rocketmq-cpp-client 是rocketmq c++版本的 所以我们C++ 开发者使用此项目 构建 获 ...
- 借助Docker搭建JMeter+Grafana+Influxdb监控平台
我们都知道Jmeter提供了原生的结果查看,既然有原生的查看结果,为什么还要多此一举使用其他工具进行查看呢,除了查看内容丰富外还有最主要的原因:Jmeter提供的查看结果插件本身是比较消耗性能的,所以 ...
- LeetCode 二分查找模板 II
模板 #2: int binarySearch(vector<int>& nums, int target){ if(nums.size() == 0) return -1; in ...