除了使用Net Core 内置的 一些AOP 咱们也可以使用一些AOP 插件
1 事务的AOP 其实也可以简单的理解成一个过滤器了 执行前 执行中 执行后
using AspectCore.DynamicProxy;
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());