dotnetcore / AspectCore-Framework

AspectCore is an AOP-based cross platform framework for .NET Standard.
MIT License
1.69k stars 324 forks source link

同一个接口下多个方法有拦截,相互调用只有第一个拦截生效 #302

Closed my6521 closed 1 year ago

my6521 commented 1 year ago

问题:TestService上Say1()上的拦截可以正常运行,Say2()上的拦截不运行。

1、版本:

<PackageReference Include="AspectCore.Extensions.DependencyInjection" Version="2.3.0" />

2、引用:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
    }
services.AddScoped<ITestService, TestService>();

3、拦截

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class TestAopAttribute : AbstractInterceptorAttribute
    {
        public string Name { get; set; }

        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var logger = context.ServiceProvider.GetService<ILogger<TestAopAttribute>>();
            logger.LogDebug(Name);
            await next(context);
        }
    }

4、接口

public interface ITestService
    {
        Task Say1();

        Task Say2();
    }

    public class TestService : ITestService
    {
        [TestAop(Name = "say1")]
        public virtual Task Say1()
        {
            return this.Say2();
        }

        [TestAop(Name = "say2")]
        public virtual Task Say2()
        {
            //
            return Task.CompletedTask;
        }
    }

5、测试调用

var testService = app.ApplicationServices.GetRequiredService<ITestService>();
testService.Say1().GetAwaiter().GetResult();
my6521 commented 1 year ago

问题已解决