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);

posted on 2017-07-26 16:59  伈隨夢飛  阅读(165)  评论(0编辑  收藏  举报

导航