通过unget 安装Castle.Windsor
using Castle.DynamicProxy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AOP_Demo { public class MyInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { PreProceed(invocation); //如果是通过实现类创建的代理,才可以执行下面,也就是调用方法 //invocation.Proceed(); Console.WriteLine(invocation.Method.Name); PostProceed(invocation); //invocation.ReturnValue 给调用方法返回的值 //invocation.Arguments 传进来的参数 } public void PreProceed(IInvocation invocation) { Console.WriteLine("方法执行前"); } public void PostProceed(IInvocation invocation) { Console.WriteLine("方法执行后"); } } public class User { public string Name { get; set; } public string PassWord { get; set; } } public interface IUserProcessor { void RegUser(User user); } public class UserProcessor : IUserProcessor { public virtual void RegUser(User user) { Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.PassWord); } } }
调用
using Castle.DynamicProxy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AOP_Demo { class Program { static void Main(string[] args) { ProxyGenerator generator = new ProxyGenerator(); MyInterceptor interceptor = new MyInterceptor(); //通过实现类创建代理 //UserProcessor userprocessor = generator.CreateClassProxy<UserProcessor>(interceptor); //通过接口 创建代理 自动生成实现接口类(操作il代码 .net emit) IUserProcessor userProcessor = generator.CreateInterfaceProxyWithoutTarget<IUserProcessor>(interceptor); User user = new User() { Name = "lee", PassWord = "123123123123" }; userProcessor.RegUser(user); Console.ReadKey(); } } }