直接使用
1.先引入程序集Castle.Core 以及Autofac.Extras.DynamicProxy
2.创建一个类继承IInterceptor并实现里面的方法
public class CustomLogInterceptor:IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("前置拦截");
invocation.Proceed();
Console.WriteLine("后置拦截");
}
}
3.添加特性
[Intercept( typeof(CustomLogInterceptor) )]
public interface IHeadphone
{
public void TestHeadPhone();
}
4.使用
ContainerBuilder containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<CustomLogInterceptor>();
// 使用EnableInterfaceInterceptors方法之前要引入 Autofac.Extras.DynamicProxy 程序集
containerBuilder.RegisterType<Headphone>().As<IHeadphone>().EnableInterfaceInterceptors();
IContainer container = containerBuilder.Build();
IHeadphone headphone = container.Resolve<IHeadphone>();
headphone.TestHeadPhone();
整合Asp.Net Core
1.同样要引入两个程序集Castle.Core 以及Autofac.Extras.DynamicProxy
2.替换容器工厂 -- 把Autofac的容器工厂植入容器工厂
builder.Host.UseServiceProviderFactory( new AutofacServiceProviderFactory());
3.配置依赖注入的抽象与具体之间的关系
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
// 在接口IHeadphone上需要加上特性 [Intercept( typeof(CustomLogInterceptor) )]
builder.RegisterType<Headphone>().As<IHeadphone>()
.EnableInterfaceInterceptors();
});