• c# aop


    核心代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Remoting.Activation;
    using System.Runtime.Remoting.Messaging;
    using System.Runtime.Remoting.Proxies;
    using System.Text;
    
    namespace Da.Extend
    {
      
    using Castle.MicroKernel;
    using Castle.Windsor;
    using Castle.Windsor.Configuration.Interpreters;
    using Castle.Windsor.Installer;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Da.Extend
    {
        public class CastleContainer
        {
            private static readonly object _locker = new object();
            private static CastleContainer _instance;
            private static IKernel _kernel;
    
            private CastleContainer()
            {
                Castle.Core.Resource.ConfigResource source = new Castle.Core.Resource.ConfigResource("castle");
                XmlInterpreter interpreter = new XmlInterpreter(source);
                IWindsorContainer windsor= new WindsorContainer(interpreter);
                _kernel = windsor.Kernel;
            }
    
            public static CastleContainer CreateInstance()
            {
                if (_instance == null)
                {
                    lock (_locker)
                    {
                        if (_instance == null)
                        {
                            _instance = new CastleContainer();
                        }
                    }
                }
                return _instance;
            }
    
            public T Resolve<T>()
            {
                return _kernel.Resolve<T>();
            }
    
    
        }
    }
    
    
    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor"/>
      </configSections>
      <castle>
        <components>
          <component   id="IUserDao"   service="Da.Dao.IUserDao,Da.Dao"   type="Da.Dao.UserDao,Da.Dao" />
        </components>
      </castle>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
      </startup>
    </configuration>
    
    
     var userService = new UserService();
     userService.usrDao = CastleContainer.CreateInstance().Resolve<IUserDao>();
     userService.Add(10);
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Remoting.Activation;
    using System.Runtime.Remoting.Messaging;
    using System.Runtime.Remoting.Proxies;
    using System.Text;
    
    namespace Da.Extend
    {
    
    
        public class AopProxy : RealProxy
        {
            public AopProxy(Type serverType): base(serverType){}
    
            /// <summary>
            /// 拦截统一方法
            /// </summary>
            /// <param name="msg"></param>
            /// <returns></returns>
            public override IMessage Invoke(IMessage msg)
            {
                IMessage message=null;
                try
                {
                    if (msg is IConstructionCallMessage)
                    {
                        IConstructionCallMessage callMsg = msg as IConstructionCallMessage;
                        object[] args = callMsg.Args;
                        BeforeConstructProceed(ref callMsg);
                        IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject((IConstructionCallMessage)msg);
                        AfterConstructProceed(ref callMsg);
                        RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue);
                        message = constructionReturnMessage;
                    }
                    else if (msg is IMethodCallMessage)
                    {
                        IMethodCallMessage callMsg = msg as IMethodCallMessage;
                        object[] args = callMsg.Args;
                        object result = null;
                        BeforeMethodProceed(ref callMsg);
                        result = callMsg.MethodBase.Invoke(GetUnwrappedServer(), args);
                        AfterMethodProceed(ref callMsg);
                        message = new ReturnMessage(result, args, args.Length, callMsg.LogicalCallContext, callMsg);
                    }
                }
                catch (Exception ex)
                {
                    message = null;
                    throw ex;
                }
                return message;
            }
    
    
            /// <summary>
            /// 调用构造函数方法前拦截
            /// </summary>
            /// <param name="callMsg"></param>
            public virtual void BeforeConstructProceed(ref IConstructionCallMessage callMsg)
            {
                Console.WriteLine("调用前的拦截器,构造函数参数数量:{0}。", callMsg.Args.Length);
            }
    
             /// <summary>
            /// 调用构造函数方法后拦截
            /// </summary>
            /// <param name="callMsg"></param>
            public virtual void AfterConstructProceed(ref IConstructionCallMessage callMsg)
            {
                Console.WriteLine("调用后的拦截器,构造函数参数数量:{0}。", callMsg.Args.Length);
            }
    
            /// <summary>
            /// 调用普通方法前拦截
            /// </summary>
            /// <param name="callMsg"></param>
            public virtual void BeforeMethodProceed(ref IMethodCallMessage callMsg)
            {
                Console.WriteLine("调用普通方法前的拦截器,方法参数是1:{0}。", callMsg.Args[0]);
            }
    
            /// <summary>
            /// 调用普通方法后拦截
            /// </summary>
            /// <param name="callMsg"></param>
            public virtual void AfterMethodProceed(ref IMethodCallMessage callMsg)
            {
                Console.WriteLine("调用普通方法后的拦截器,方法参数是1:{0}。", callMsg.Args[0]);
            }  
       }
    
        /// <summary>
       /// Aop特性类
       /// </summary>
       public class AopAttribute : ProxyAttribute
       {
           /// <summary>
           /// 创建对象实例
           /// </summary>
           /// <param name="serverType"></param>
           /// <returns></returns>
           public override MarshalByRefObject CreateInstance(Type serverType)
           {
               AopProxy realProxy = new AopProxy(serverType);
               return realProxy.GetTransparentProxy() as MarshalByRefObject;
           }
       }
    
    }

    配置代码:

     [AopAttribute]
        public class UserService:ContextBoundObject
        {
            public IUserDao usrDao { get; set; }
    
            //private IUserDao usrDao = new UserDao();
    
            //private UserDao usrDao = new UserDao();
    
            public UserService()
            {
                Console.WriteLine("这是UserService的构造函数");
            }
    
            public virtual void Add(int userId)
            {
                if (usrDao != null)
                {
                    usrDao.Add(userId);
                }
            }
    
        }

    调用代码:

    var userService = new UserService();
    userService.usrDao = CastleContainer.CreateInstance().Resolve<IUserDao>();
    userService.Add(10);
  • 相关阅读:
    HDU 2842 (递推+矩阵快速幂)
    HDU 2838 (DP+树状数组维护带权排序)
    HDU 2836 (离散化DP+区间优化)
    HDU 2831 (贪心)
    HDU 2818 (矢量并查集)
    HDU 2822 (BFS+优先队列)
    HDU 3090 (贪心)
    HDU 3089 (快速约瑟夫环)
    XCOJ 1103 (LCA+树链最大子段和)
    HDU 3078 (LCA+树链第K大)
  • 原文地址:https://www.cnblogs.com/joyet-john/p/7240638.html
Copyright © 2020-2023  润新知