經過動態代理模式Interceptor實如今RegUser()方法自己業務先後加上一些本身的功能,如:PreProceed和PostProceed,即不修改UserProcessor類又能增長新功能spa
public interface IUserProcessor { void RegUser(User user); }
public class UserProcessor : IUserProcessor { /// <summary> /// 必須帶上virtual 不然無效 /// </summary> /// <param name="user"></param> public virtual void RegUser(User user) { Console.WriteLine($"用戶已註冊。Name:{user.Name},PassWord:{user.Password}"); } }
public class MyInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { PreProceed(invocation); invocation.Proceed();//就是調用原始業務方法 PostProceed(invocation); } public void PreProceed(IInvocation invocation) { Console.WriteLine("方法執行前"); } public void PostProceed(IInvocation invocation) { Console.WriteLine("方法執行後"); } }
調用代理
/// <summary> /// 使用Castle\DynamicProxy 實現動態代理 /// 方法必須是虛方法 /// </summary> public class CastleProxyAOP { public static void Show() { User user = new User() { Name = "Eleven", Password = "123456" }; ProxyGenerator generator = new ProxyGenerator(); MyInterceptor interceptor = new MyInterceptor(); UserProcessor userprocessor = generator.CreateClassProxy<UserProcessor>(interceptor); userprocessor.RegUser(user); } }