1、Nuget引入程序集
2、扩展IInterceptor
public class CusotmInterceptor : IInterceptor
{
/// <summary>
/// 切入者逻辑
///
/// 使用了Intercept 方法把 要调用的Call方法给包裹起来了
/// </summary>
/// <param name="invocation"></param>
public void Intercept(IInvocation invocation)
{
{
Console.WriteLine("Before");
}
invocation.Proceed(); //这句话的执行就是要去执行真实的方法
{
Console.WriteLine("After");
}
}
}
3、注册对象和具体之间的关系的时候,需要执行要支持AOP扩展EnableClassInterceptors
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());//通过工厂替换,把Autofac整合进来
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
containerBuilder.RegisterType<Microphone>().As<IMicrophone>();
containerBuilder.RegisterType<Power>().As<IPower>();
containerBuilder.RegisterType<Headphone>().As<IHeadphone>();
containerBuilder.RegisterType<ApplePhone>().As<IPhone>()
//.EnableClassInterceptors(); //当前的配置 要支持AOP扩展--通过类来支持
.EnableInterfaceInterceptors(new ProxyGenerationOptions()
{
Selector = new CustomInterceptorSelector()
});
containerBuilder.RegisterType<CusotmInterceptor>();
containerBuilder.RegisterType<CusotmLogInterceptor>();
containerBuilder.RegisterType<CusotmCacheInterceptor>();
//注册每个控制器和抽象之间的关系
var controllerBaseType = typeof(ControllerBase);
containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired(new CusotmPropertySelector()); //支持属性注入
});
//支持控制器的实例让IOC容器来创建---autofac来创建
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
4.把要扩展aop的方法定义为 virtual 方法
[Intercept(typeof(CusotmInterceptor))]
public class ApplePhone : IPhone
{
public IMicrophone Microphone { get; set; }
public IHeadphone Headphone { get; set; }
public IPower Power { get; set; }
public ApplePhone(IHeadphone iHeadphone)
{
this.Headphone = iHeadphone;
Console.WriteLine("{0}带参数构造函数", this.GetType().Name);
}
public virtual void Call()
{
Console.WriteLine("{0}打电话", this.GetType().Name); ;
}
public void Text()
{
Console.WriteLine("{0}发信息", this.GetType().Name); ;
}
}
5.把扩展的IInterceptor 也要注册到容器中去
containerBuilder.RegisterType<CusotmInterceptor>();