• .Net学习之面向切面编程(AOP)


    结合设计模式,通过代码理解面向切面编程,

    通过,结构型设计模式,装饰器模式来实现AOP,代码如下

     /// <summary>
        /// 装饰器模式实现静态代理
        /// AOP 在方法前后增加自定义的方法
        /// </summary>
        public class DecoratorAOP
        {
            public static void Show()
            {
                User user = new User()
                {
                    Name = "Eleven",
                    Password = "123123123123"
                };
                //直接调用
                IUserProcessor processor = new UserProcessor();
                processor.RegUser(user);
                Console.WriteLine("***************");
                //通过装饰器模式,在方法执行前后添加功能
                processor = new UserProcessorDecorator(processor);
                processor.RegUser(user);
            }
    
            public interface IUserProcessor
            {
                void RegUser(User user);
            }
            public class UserProcessor : IUserProcessor
            {
                public void RegUser(User user)
                {
                    Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.Password);
                }
            }
    
            /// <summary>
            /// 装饰器的模式去提供一个AOP功能
            /// </summary>
            public class UserProcessorDecorator : IUserProcessor
            {
                private IUserProcessor _UserProcessor { get; set; }
                public UserProcessorDecorator(IUserProcessor userprocessor)
                {
                    this._UserProcessor = userprocessor;
                }
    
                public void RegUser(User user)
                {
                    BeforeProceed(user);
    
                    this._UserProcessor.RegUser(user);
    
                    AfterProceed(user);
                }
    
                /// <summary>
                /// 业务逻辑之前
                /// </summary>
                /// <param name="user"></param>
                private void BeforeProceed(User user)
                {
                    Console.WriteLine("方法执行前");
                }
                /// <summary>
                /// 业务逻辑之后
                /// </summary>
                /// <param name="user"></param>
                private void AfterProceed(User user)
                {
                    Console.WriteLine("方法执行后");
                }
            }
    
        }

    通过,结构型设计模式,代理模式来实现AOP,代码如下

       /// <summary>
        /// 代理模式实现静态代理
        /// AOP 在方法前后增加自定义的方法
        /// </summary>
        public class ProxyAOP
        {
            public static void Show()
            {
                User user = new User()
                {
                    Name = "Eleven",
                    Password = "123123123123"
                };
                IUserProcessor processor = new UserProcessor();
                //直接调用方法
                processor.RegUser(user);
                Console.WriteLine("***************");
                //实现AOP,在执行前后加其他方法
                processor = new ProxyUserProcessor();
                processor.RegUser(user);
            }
    
            public interface IUserProcessor
            {
                void RegUser(User user);
            }
            public class UserProcessor : IUserProcessor
            {
                public void RegUser(User user)
                {
                    Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.Password);
                }
            }
    
            /// <summary>
            /// 代理模式去提供一个AOP功能
            /// </summary>
            public class ProxyUserProcessor : IUserProcessor
            {
                private IUserProcessor _UserProcessor = new UserProcessor();
    
                public void RegUser(User user)
                {
                    BeforeProceed(user);
                    this._UserProcessor.RegUser(user);
                    AfterProceed(user);
                }
    
                /// <summary>
                /// 业务逻辑之前
                /// </summary>
                /// <param name="user"></param>
                private void BeforeProceed(User user)
                {
                    Console.WriteLine("方法执行前");
                }
                /// <summary>
                /// 业务逻辑之后
                /// </summary>
                /// <param name="user"></param>
                private void AfterProceed(User user)
                {
                    Console.WriteLine("方法执行后");
                }
            }
    
        }

    通过Unity实现AOP,配置太复杂就不贴了。。。就一个实现类的代码,可以用于添加方法的日志,异常处理,不用修改方法本身,不用挨个方法+Log.Info()了,通过Unity(IOC)创建的对象都能用,代码如下

     public class LogBeforeBehavior : IInterceptionBehavior
        {
            public IEnumerable<Type> GetRequiredInterfaces()
            {
                return Type.EmptyTypes;
            }
            public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
            {
                Console.WriteLine("LogBeforeBehavior");
                Console.WriteLine(input.MethodBase.Name);
                foreach (var item in input.Inputs)
                {
                    Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
                    //反射&序列化获取更多信息
                }
                return getNext().Invoke(input, getNext);//
            }
    
            public bool WillExecute
            {
                get { return true; }
            }
        }

     再加一个Unity创建对象和调用的代码吧,NuGet添加Unity的引用

    public class UnityConfigAOP
        {
            public static void Show()
            {
                User user = new User()
                {
                    Name = "Eleven",
                    Password = "12345678934534643"
                };
                 //这个是代码块,好神奇的呦
                {
                    //配置UnityContainer
                    IUnityContainer container = new UnityContainer();
                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                    fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\Unity.Config");
                    Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
                    configSection.Configure(container, "aopContainer");
    
                    IUserProcessor processor = container.Resolve<IUserProcessor>();
                    processor.RegUser(user);
    
                }
            }
        }    

     

  • 相关阅读:
    MySQL 获得 当前日期时间 函数
    07/26/2019 00:38:17 INFO macOS users need to install XQuartz. See https://support.apple.com/en-gb/HT201341
    ModuleNotFoundError: No module named 'pynvx'
    ModuleNotFoundError: No module named 'cv2'
    ModuleNotFoundError: No module named 'tqdm'
    WARNING: You are using pip version 19.1.1, however version 19.2.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command.
    多进程和多线程的理解
    python 装饰器demo
    python 日志内容提取
    python 中 list 去重复
  • 原文地址:https://www.cnblogs.com/kongsq/p/9748763.html
Copyright © 2020-2023  润新知