简单AOP

代码如下

//使用说明
//1,新加接口与类
//2,新加类并实现ICallHandler类: ExecuteHandler
//3,新建特性并实现HandlerAttribute和重写其中的CreateHandler方法:ExecuteAttribute
//4,在接口上使用ExecuteAttribute特性
//5,在调用之前应设置拦截类,没有第二句代码,方法不会进入到ExecuteHandler.Invoke方法中
//   var container1 = new UnityContainer().AddNewExtension<Interception>().RegisterType<Interface1, Class1>();
//   container1.Configure<Interception>().SetInterceptorFor<Interface1>(new InterfaceInterceptor());
//6,调用
//注:第5,6说的就是 Main里面的方法。

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var container1 = new UnityContainer().AddNewExtension<Interception>().RegisterType<Interface1, Class1>();
            container1.Configure<Interception>().SetInterceptorFor<Interface1>(new InterfaceInterceptor());
           
            var sample1 = container1.Resolve<Interface1>();
            sample1.Add();
            Console.ReadLine();
        }
    }

    [Execute]
    public interface Interface1
    {
        void Add();
        void Delete();
    }

    public class Class1:Interface1
    {
        public void Add()
        {
            Console.WriteLine("Add成功!");
        }

        public void Delete()
        {
            Console.WriteLine("Delete成功!");
        }
    }

    public class ExecuteHandler : ICallHandler
    {
        public int Order
        {
            get;
            set;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {            
            //getNext()(input,getNext)就是具体的执行方法。在这之前或之后你可以做一些其它事情,如记录日志,判断是否有权限操作之类的。
            var retvalue = getNext()(input, getNext);
            return retvalue;
        }        
    }

    public class ExecuteAttribute : HandlerAttribute
    {
        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
        {
            return new ExecuteHandler();
        }
    }
}

代码下载

原文地址:https://www.cnblogs.com/pnljs/p/3791423.html