AspectCore操作aop

AspectCore是一个很好的aop矿建,能够很好的支持async,我这边是使用autofac作为依赖注入容器,

在nuget上直接安装AspectCore.Extensions.Autofac,就可以使用了。

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");
        }
    }
View Code

属性注入有两种方法:

1.以特性注入的方式:

/// <summary>
        /// 
        /// </summary>
        [FromServiceContext]
        public ITestThree TestThree { get; set; }
View Code

2.使用ioc获取

  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");
        }
View Code
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值