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. 使用@Cacheable注解时,Redis连不上,直接调用方法内部的解决方案

    最近redis 域名一致解析错误,导致业务多了很多异常.那么如何在这种情况下直接访问数据库,而不是报错呢 1. 解决方案 其实很简单,在配置 redis 时,只需要多一项配置,继承 CachingCo ...

  2. List<bean> 转换成List<Map>

    //将listmap转换成list实体类 List<OaAttachment>list=new ArrayList<OaAttachment>(); if(Func.isNot ...

  3. java代理(静态代理和jdk动态代理以及cglib代理)

    版权声明:本文为Fighter168原创文章,未经允许不得转载.   目录(?)[+]   说到代理,脑袋中浮现一大堆代理相关的名词,代理模式,静态代理,jdk代理,cglib代理等等. 记忆特别深刻 ...

  4. Intellij IDEA设置

    代码格式化/保存时自动格式 搜索google-java-format 和 Save Actions,安装 保存时候// 自动空格 自动导包 自动换行

  5. Asp.net Core 2.0 实现Cookie会话

    与1.0版本相比微软做了一些调整.详细请参考官方文档,我这里就讲2.0的吧 1.首先要在 根目录下 Startup.cs 类中启用 cookie会话,有两处要配置 第一处在  public void ...

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

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

  7. C#扫盲篇(二)依赖倒置•控制反转•依赖注入•面向接口编程--满腹经纶的说

    扫盲系列的文章收到了广大粉丝朋友的支持,十分感谢,你们的支持就是我最大动力. 我的扫盲系列还会继续输出,本人也是一线码农,有什么问题大家可以一起讨论.也可以私信或者留言您想要了解的知识点,我们一起进步 ...

  8. spark进行相同列的join时,只留下A与B关系,不要B与A

    一.问题需求: 近期需要做一个商品集合的相关性计算,需要将所有商品进行两两组合笛卡尔积,但spark自带的笛卡尔积会造成过多重复,而且增加join量 假如商品集合里面有: aa   aa bb   b ...

  9. java:原子类的CAS

    当一个处理器想要更新某个变量的值时,向总线发出LOCK#信号,此时其他处理器的对该变量的操作请求将被阻塞,发出锁定信号的处理器将独占共享内存,于是更新就是原子性的了. 1.compareAndSet- ...

  10. shelll中test命令的使用【转】

    Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值.字符和文件三个方面的测试. 数值测试 参数 说明 -eq 等于则为真 -ne 不等于则为真 -gt 大于则为真 -ge 大于等于 ...