这里使用的是AspectCore.Extensions.DependencyInjection这个nuget包,地址是https://www.nuget.org/packages/AspectCore.Extensions.DependencyInjection/

安装完这个包之后,第一步,需要在startup文件中添加如下代码

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    /* register service */
    return services.ToServiceContainer().Build();
}

这个包可以实现属性注入以及动态代理,动态代理有两种方式,这里介绍使用Attribute的方式。

public class LogRecordInterceptorAttribute : AbstractInterceptorAttribute
{
    // 属性注入
    [FromContainer]
    public ILogger<LogRecordInterceptorAttribute> Logger { get; set; }

    public override async Task Invoke(AspectContext context, AspectDelegate next)
    {
        MethodInfo method = context.ImplementationMethod;
        string invokeMessage = $"{method.DeclaringType.Name}.{method.Name}()";

        Logger.LogTrace($"{invokeMessage}..."); // 方法调用之前
        await context.Invoke(next);
        Logger.LogTrace(invokeMessage); // 方法调用之后
    }
}

对于需要注入的属性,使用FromContainer进行标注。InterceptorAttribute标签可以放在类上和方法上。


版权声明:本文为weixin_31317775原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_31317775/article/details/84570243