解惑下,以下代码在实现一个接口情况下可以 aop吗
Opened this issue · 1 comments
gainorloss commented
目标接口
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" />
liuhaoyang commented
问题应该出在这个函数上
Task<bool> IApplicationEventListener.HandleAsync(ApplicationEvent e) => HandleAsync((T)e);
之后看看这个语法怎么兼容