Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

解惑下,以下代码在实现一个接口情况下可以 aop吗 #319

Open
gainorloss opened this issue Jan 8, 2024 · 1 comment
Open

Comments

@gainorloss
Copy link

gainorloss commented Jan 8, 2024

目标接口

  public class SimpleEventListener
    //: IApplicationEventListener<SimpleEvent>
{
    private readonly ILogger<SimpleEventListener> _logger;

    public SimpleEventListener(ILogger<SimpleEventListener> logger)
    {
        _logger = logger;
    }

    [OperationLogging("简单消息订阅")]
   public async virtual Task<bool> HandleAsync(SimpleEvent e)
   {
     _logger.LogInformation($"{nameof(SimpleEventListener)}:{e.Name}");
     await Task.Delay(10);
     return true;
   }
}

IApplicationEventListener 不实现的时候是没问题的,实现的时候,拦截报错如下
Declaration referenced in a method implementation cannot be a final method. Type: 'AspectCore.DynamicGenerated.SimpleEventListener'. Assembly: 'AspectCore.DynamicProxy.Generator, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

补充:
使用方法

services.ConfigureDynamicProxy()
services.AddTransient<SimpleEventListener>();
hostBuilder.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());

拦截器标注定义和 IApplicationListener 定义

public class OperationLoggingAttribute : AbstractInterceptorAttribute
{
    public string Name { get; protected set; }
    public OperationLoggingAttribute(string name)
    {
        Name = name;
    }
    public override async Task Invoke(AspectContext context, AspectDelegate next)
    {
        var logger = context.ServiceProvider.GetService<ILogger<OperationLoggingAttribute>>();
        logger.LogInformation("{0} starting...", Name);
        await next(context);
        logger.LogInformation("{0} ended", Name);
    }
}
public interface IApplicationEventListener
{
    Task<bool> HandleAsync(ApplicationEvent e);
}

public interface IApplicationEventListener<T> : IApplicationEventListener
    where T : ApplicationEvent
{
    Task<bool> HandleAsync(T e);

    Task<bool> IApplicationEventListener.HandleAsync(ApplicationEvent e) => HandleAsync((T)e);
}

nuget:
<PackageReference Include="aspectcore.extensions.dependencyinjection" Version="2.4.0" />

@gainorloss gainorloss changed the title 解惑下,以下代码在继承一个接口情况下可以 aop吗 解惑下,以下代码在实现一个接口情况下可以 aop吗 Jan 10, 2024
@liuhaoyang
Copy link
Member

问题应该出在这个函数上

  Task<bool> IApplicationEventListener.HandleAsync(ApplicationEvent e) => HandleAsync((T)e);

之后看看这个语法怎么兼容

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants