AspectCore是一个很好的aop矿建,能够很好的支持async,我这边是使用autofac作为依赖注入容器,
在nuget上直接安装AspectCore.Extensions.Autofac,就可以使用了。
![](https://img-blog.csdnimg.cn/img_convert/eae7cd1d4a4689442d9ba33f840e7638.gif)
![](https://img-blog.csdnimg.cn/img_convert/b692daebbba1cacdcee1b5bf04b7b2e4.gif)
class Program
{
static async Task Main(string[] args)
{
ContainerBuilder builder=new ContainerBuilder();
builder.RegisterType<MainModel>();
builder.RegisterType<TestThree>().As<ITestThree>();
builder.RegisterType<MainModelAsync>();
builder.RegisterDynamicProxy();
var container=builder.Build();
container.Resolve<MainModel>().Test();
await container.Resolve<MainModelAsync>().TestAsync();
}
}
public class MainModel
{
[TestTwo]
[TestOne]
public virtual void Test()
{
Console.WriteLine("test");
}
}
public class MainModelAsync
{
[TestTwo]
[TestOne]
public virtual async Task TestAsync()
{
await Task.Delay(1000);
Console.WriteLine("test");
}
}
public class TestOneAttribute : AbstractInterceptorAttribute
{
/// <summary>
///
/// </summary>
[FromServiceContext]
public ITestThree TestThree { get; set; }
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
TestThree.Test();
Console.WriteLine("one start");
await next(context);
Console.WriteLine("one end");
}
}
public class TestTwoAttribute : AbstractInterceptorAttribute
{
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
var testThree = context.ServiceProvider.Resolve<ITestThree>();
testThree.Test();
Console.WriteLine("two start");
await next(context);
Console.WriteLine("two end");
}
}
public interface ITestThree
{
void Test();
}
public class TestThree:ITestThree
{
public void Test()
{
Console.WriteLine("test three");
}
}
属性注入有两种方法:
1.以特性注入的方式:
![](https://img-blog.csdnimg.cn/img_convert/52c55a6e6730451026876267fd649595.gif)
![](https://img-blog.csdnimg.cn/img_convert/6f7a5f2cb4241e3493701bb6ba195fb3.gif)
/// <summary>
///
/// </summary>
[FromServiceContext]
public ITestThree TestThree { get; set; }
2.使用ioc获取
![](https://img-blog.csdnimg.cn/img_convert/06c882247823024bfd00b2473142dbb3.gif)
![](https://img-blog.csdnimg.cn/img_convert/4bd7fcb801efb820f4020dc242994584.gif)
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
var testThree = context.ServiceProvider.Resolve<ITestThree>();
testThree.Test();
Console.WriteLine("two start");
await next(context);
Console.WriteLine("two end");
}