控制檯應用程式使用Autofac實現AOP介面代理攔截
阿新 • • 發佈:2021-01-19
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 } }
執行結果:
參考資源