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. java 合并两个list 并去重

    //两个list合并并去除重复 public static void main(String[] args) throws Exception { List list1 =new ArrayList( ...

  2. [leetcode]168. Excel Sheet Column Title表格列名编码(十进制和多进制相互转换)

    其实就是一道,十进制转多进制的题 十进制转多进制就是从后边一位一位地取数. 这种题的做法是,每次用n%进制,相当于留下了最后一位,然后把这位添加到结果最前边.结果需要转为进制的符号. 下一次循环的n变 ...

  3. Android猜数字大小游戏

    功能介绍:该程序能够提示猜大了猜小了,并且对空白输入处理,还对猜测次数限制,提供重置功能. 1.先看界面,一个输入框EditText,两个Button 2.界面设计  activity_main2.x ...

  4. Vue - MVVM模式及优点

    MVVM模式 视图层和数据层的双向绑定,让我们无需再去关心DOM操作的事情,更多的精力放在数据和业务逻辑上去 MVVM是Model-View-ViewModel的缩写.MVVM是一种设计思想. Mod ...

  5. dp的冗余(选数类)

    我们先来看一个例题: 在一个长度为n的序列中选出任意个数的数,要求每m个数中至少一个被选,要求选的数之和最小化. 我们很容易想出用f[i][j]来表示前i个数选的最后一个数是j,也就有 for(int ...

  6. 每日一个linux命令6 -- rmdir

    rmdir doc 如果doc为空目录则删除,否则无法删除. rmdir -p test2/test3 递归删除空目录,首先判断test3,如果test3为空,则删除test3,此时判断test2,如 ...

  7. 初学VBA

    一个最基本的VBA程序 Sub test() //宏开始 Dim ge As Range //定义变量 For Each ge In Range("a1:a10") //从a1到a ...

  8. [ABP教程]第七章 作者:数据库集成

    Web开发教程7 作者:数据库集成 关于此教程 在这个教程系列中,你将要构建一个基于ABP框架的应用程序 Acme.BookStore.这个应用程序被用于甘丽图书页面机器作者.它将用以下开发技术: E ...

  9. 【JavaWeb】Servlet 程序

    Servlet 程序 Servlet Servlet 是在 Web 服务器中运行的小型 Java 程序.Servlet 通常通过 HTTP(超文本传输​​协议)接收和响应来自 Web 客户端的请求. ...

  10. LeetCode700 二叉搜索树中搜索

    给定二叉搜索树(BST)的根节点和一个值. 你需要在BST中找到节点值等于给定值的节点. 返回以该节点为根的子树. 如果节点不存在,则返回 NULL. 例如, 给定二叉搜索树: 4 / \ 2 7 / ...