基于DispatchProxy打造自定义AOP组件

DispatchProxy是微软爸爸编写的一个代理类,基于这个,我扩展了一个AOP组件

暂时不支持依赖注入构造方法,感觉属性注入略显麻烦,暂时没打算支持

基于特性的注入流程

    [AttributeUsage(AttributeTargets.Method)]
    internal class TestAttribute:AopAttribute
    {
        protected override Task BeforeAsync(MethodInfo targetMethod, object[] args)
        {
            Console.WriteLine($"BeforeAsync {targetMethod.Name}");
            return base.BeforeAsync(targetMethod, args);
        }

        protected override Task AfterAsync(MethodInfo targetMethod, object[] args)
        {
            Console.WriteLine($"AfterAsync {targetMethod.Name}");

            return base.AfterAsync(targetMethod, args);
        }
    }

编写接口

    public interface ITest
    {
        [Test]
        void TestVoid();
        [Test]
        int TestInt();
        [Test]
        Task TestAsync();
        [Test]
        Task<int> TestIntAsync();
    }

整体结构是依赖注入,再实现一个实现类就好

特性打在接口的方法上

刚开坑,暂时只支持特性对应方法

调用

services.AddNCoreCoderAop<ITest, Test>(ServiceLifetime.Transient);

方法支持同步和异步两种

支持Singleton、Scoped、Transient三种生命周期,默认生命周期是Singleton

项目地址:

https://github.com/htrlq/NCoreCoder.Framework

猜你喜欢

转载自www.cnblogs.com/NCoreCoder/p/11492755.html
今日推荐