在ABP中实现自定义拦截器(AOP)

发布时间 2023-09-20 17:37:17作者: 竹林听雨行

实现Aop拦截器
首先在Domain.Shared中创建Interceptors文件夹。
创建LogInterceptor日志拦截类和LogAttribute特性类。代码结构如下:

[Dependency(ServiceLifetime.Transient)]
public class LogInterceptor : AbpInterceptor
{
    public override async Task InterceptAsync(IAbpMethodInvocation invocation)
    {
        Console.WriteLine("方法操作前日志");
        await invocation.ProceedAsync();
        Console.WriteLine("方法操作后日志");
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class LogAttribute : Attribute
{
    public LogAttribute()
    {

    }
}

 

在模块类中的PreConfigureServices()方法中注册我们的拦截器:

public override void PreConfigureServices(ServiceConfigurationContext context)
{
    //注册拦截器(AOP)对IOC的类进行代理
    context.Services.OnRegistred(options =>{
        if (options.ImplementationType.IsDefined(typeof(LogAttribute), true))
        {
           options.Interceptors.TryAdd<LogInterceptor>();  
        }
    } 
}

 

 

在需要拦截的类上添加特性标记拦截:

[LogAttribute] // 使用特性标记要拦截的类
public class MyService : ITransientDependency
{
    [LogAttribute] // 使用特性标记要拦截的方法
    public void MyMethod()
    {
        // 方法实现
    }
}

 


————————————————
版权声明:本文为CSDN博主「琉璃知我心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_36668541/article/details/129999753