asp.net core 基于autofac 实现AOP 拦截 之 第二种方式 -基于class

Autofac 官方地址:https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html

(1)引用 nuget :Autofac.Extensions.DependencyInjection  Autofac.Extras.DynamicProxy

(2)修改入口文件

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                //改用Autofac来实现依赖注入
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    
                });

(3)修改startup 文件

     //autofac 新增
        public ILifetimeScope AutofacContainer { get; private set; }
  public void ConfigureContainer(ContainerBuilder builder)
        {
}

(4)创建AOP拦截文件

using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Aufac
{
    public class CacheIntercept : IInterceptor
    {
        public CacheIntercept()
        { }
        public void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget ?? invocation.Method;
            Debug.WriteLine("before");
            invocation.Proceed();
            Debug.WriteLine("end");
        }
    }
}

(4)应用拦截效果

      4-1 使用类进行AOP

       4.1.1 创建以下类文件

using Autofac.Extras.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Aufac
{
    /// <summary>
    /// 类的AOP方式1
    /// </summary>
    [Intercept("datacache")]
    public class AufacClass1
    {
        /// <summary>
        /// 必须是virtual
        /// </summary>
        /// <returns></returns>
        public virtual string GetName()
        {
            Debug.WriteLine("this is getname");
            return "this is getname";
        }
    }
}

 

4.1.2配置startup 注入到服务

        //autofac 新增
        public void ConfigureContainer(ContainerBuilder builder)
        {
           builder.RegisterType<WebApplication1.Aufac.AufacClass1>().EnableClassInterceptors();
            builder.Register(c => new WebApplication1.Aufac.CacheIntercept()).Named<IInterceptor>("datacache");

}

 

4.1.3在代码里调用 发现已经进行了拦截处理

调用代码如下

WebApplication1.Aufac.AufacClass1 face1;
public WeatherForecastController(WebApplication1.Aufac.AufacClass1 interFace1
)
{
face1 = interFace1;
}
[HttpGet]
//[Caching(AbsoluteExpiration =2,keyname ="id",keyvaluename ="id")]
public  string Get()
{
face1.GetName();
return DateTime.Now.ToString();
}

 

asp.net core 基于autofac 实现AOP 拦截 之 第二种方式 -基于class

上一篇:jQuery系列---【jQuery中的动画】


下一篇:Web 多媒体操作集