1 安装依赖包
2 定义拦截器类
3 定义被代理的接口和实现代理接口的类
using Autofac.Extras.DynamicProxy; using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp_AutofacAop { /// <summary> /// 定义一个接口 /// </summary> public interface IAnimal { void Test(string Name); } /// <summary> /// 继承接口,并实现方法,给类型加上特性Attribute /// </summary> [Intercept(typeof(LogInterceptor))] public class Dog : IAnimal { public void Test(string Name) { Console.WriteLine("Dog Run"); } } /// <summary> /// 继承接口,并实现方法,给类型加上特性Attribute /// </summary> [Intercept(typeof(LogInterceptor))] public class Pig : IAnimal { public void Test(string Name) { Console.WriteLine("Pig Run"); } } /// <summary> /// 继承接口,并实现方法,给类型加上特性Attribute /// </summary> [Intercept(typeof(LogInterceptor))] public class Cat : IAnimal { public void Test(string Name) { Console.WriteLine("Cat Run"); } } }
4 初始化Autofac并注册依赖
#region 在应用的启动地方构造Autofac容器并注册依赖 // 定义容器 private static IContainer Container { get; set; } /// <summary> /// 初始化Autofac /// </summary> private static void AutofacInit() { var builder = new ContainerBuilder(); // 注册依赖 builder.RegisterType<LogInterceptor>(); // 注册拦截器 builder.Register<Dog>(c => new Dog ()).As<IAnimal>().EnableInterfaceInterceptors(); builder.RegisterType<Pig>().Named<IAnimal>("Pig").EnableInterfaceInterceptors(); builder.RegisterType<Cat>().Named<IAnimal>("Cat").EnableInterfaceInterceptors(); builder.RegisterType<AnimalManager>(); Container = builder.Build(); } #endregion
5 测试
完整测试代码如下
using System; using Autofac; using Autofac.Extras.DynamicProxy; namespace ConsoleApp_AutofacAop { class Program { static void Main(string[] args) { AutofacInit(); TestMethod(); Console.ReadLine(); } #region 在应用的启动地方构造Autofac容器并注册依赖 // 定义容器 private static IContainer Container { get; set; } /// <summary> /// 初始化Autofac /// </summary> private static void AutofacInit() { var builder = new ContainerBuilder(); // 注册依赖 builder.RegisterType<LogInterceptor>(); // 注册拦截器 builder.Register<Dog>(c => new Dog ()).As<IAnimal>().EnableInterfaceInterceptors(); builder.RegisterType<Pig>().Named<IAnimal>("Pig").EnableInterfaceInterceptors(); builder.RegisterType<Cat>().Named<IAnimal>("Cat").EnableInterfaceInterceptors(); builder.RegisterType<AnimalManager>(); Container = builder.Build(); } #endregion #region 测试方法 public static void TestMethod() { using (var scope = Container.BeginLifetimeScope()) { var dog = scope.Resolve<AnimalManager>(); dog.Test("para"); var pig = scope.ResolveNamed<IAnimal>("Pig"); pig.Test("para"); var cat = scope.ResolveNamed<IAnimal>("Cat"); cat.Test("para"); } } #endregion } }
运行结果:
参考资源
https://www.cnblogs.com/tomorrow0/p/14298352.html