Skip to content

DispatchProxy 实现 AOP

DispatchProxy 是 System.Reflection 封装的类

使用 DispatchProxy 动态代理

C#
// Program.cs
// Author: xulai

using AOP;
using Service;
using System.Reflection;

IUser user = new User();
user = TransformProxy.GetDynamicProxy(user);
user.Create("Processing");

namespace Service
{
    public class User : IUser
    {
        public void Create(string name)
        {
            Console.WriteLine($"This is {name}.");
        }
    }
    public interface IUser
    {
        void Create(string name);
    }
}

namespace AOP
{
    public class CustomProxy<T> : DispatchProxy
    {
        public T? Instance { get; set; }
        protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
        {
            BeforeProcess();
            var result = targetMethod?.Invoke(Instance, args);
            AfterProcess();
            return result;
        }
        private static void BeforeProcess()
        {
            Console.WriteLine($"This is BegoreProcess.");
        }
        private static void AfterProcess()
        {
            Console.WriteLine($"This is AfterProcess.");
        }
    }
    public class TransformProxy
    {
        public static T GetDynamicProxy<T>(T instance)
        {
            object? proxy = DispatchProxy.Create<T, CustomProxy<T>>();
            if (proxy is CustomProxy<T> customProxy)
            {
                customProxy.Instance = instance;
            }
            return (T)proxy!;
        }
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度