Net Core AOP EF Core事务的统一管理

除了使用Net Core 内置的 一些AOP 咱们也可以使用一些AOP 插件

1  事务的AOP 其实也可以简单的理解成一个过滤器了 执行前  执行中 执行后 
using AspectCore.DynamicProxy;
   /// <summary>
    ///  事务  主要针对业务层 数据库处理事务
    ///  注意事项 如需要在控制器层面使用 则实现的Action 变成虚方法即可进入
    /// </summary>
    public class TransactionInterceptorAttribute : AbstractInterceptorAttribute
    {
          
   
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
          
   
            var sampledbContext = (LifeSampledbContext)context.ServiceProvider.GetService(typeof(LifeSampledbContext));
            if (sampledbContext.Database.CurrentTransaction == null)
            {
          
   
                await sampledbContext.Database.BeginTransactionAsync();
                try
                {
          
   
                    await next(context);
                    sampledbContext.Database.CommitTransaction();
                }
                catch (Exception ex)
                {
          
   
                    sampledbContext.Database.RollbackTransaction();
                    throw;
                }
            }
            else
            {
          
   
                await next(context);
            }
        }
    }
2 在 StrapUp 中   services.AddDependencyInjection();
 3 在 Program 中
      public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((context, builder) =>
                {
          
   
                    var path = Path.Combine(Directory.GetCurrentDirectory(), "Log4net.config");
                    builder.AddLog4Net(path);
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
          
   
                    webBuilder.UseStartup<Startup>();
                }).UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
经验分享 程序员 微信小程序 职场和发展