using System; using System.Linq; using Castle.DynamicProxy; namespace AopTest { class AopTest { static public void Test() { var proxyGenerator = new ProxyGenerator(); IUserService user = proxyGenerator.CreateClassProxy<UserService>(new UserRigthCheckProxy()); user.GetUser("admin"); user.GetUser("guest"); user.UpdateUser("admin"); user.UpdateUser("guest"); } } public interface IUserService { void GetUser(string userId); void UpdateUser(string userId); } public class UserService : IUserService { public virtual void GetUser(string userId) { Console.WriteLine(userId + ",Welcome!"); } public virtual void UpdateUser(string userId) { Console.WriteLine(userId + ",Updated!"); } } public class UserRigthCheckProxy : IInterceptor { private static readonly string[] RightOperations = new string[] { "UpdateUser" }; public void Intercept(IInvocation invocation) { if (invocation.Arguments.Length > 0 && invocation.Arguments[0] is string) { if (RightOperations.Contains(invocation.Method.Name)) { var userId = (string) invocation.Arguments[0]; if (userId == "admin") { Console.WriteLine("有权限操作 "); invocation.Proceed(); } else { Console.WriteLine("{0},您没有权限操作", userId); } } else { Console.WriteLine("有权限操作 "); invocation.Proceed(); } } else { invocation.Proceed(); } } } }