Skip to content

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

Open
@gainorloss

Description

@gainorloss

目标接口

  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" />

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions