Dynamic Proxy
How to make a simple dynamic proxy in C#
You could do this with a combination of System.Dynamic.DynamicObject and ImpromptuInterface but you will have to have an Interface that implements the functions and properties you want to proxy.
https://github.com/ekonbenefits/impromptu-interface
public interface IDoStuff { void Foo(); } public class Wrapper<T> : DynamicObject { private readonly T _wrappedObject; public static T1 Wrap<T1>(T obj) where T1 : class { if (!typeof(T1).IsInterface) throw new ArgumentException("T1 must be an Interface"); return new Wrapper<T>(obj).ActLike<T1>(); } //you can make the contructor private so you are forced to use the Wrap method. private Wrapper(T obj) { _wrappedObject = obj; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { try { //do stuff here //call _wrappedObject object result = _wrappedObject.GetType().GetMethod(binder.Name).Invoke(_wrappedObject, args); return true; } catch { result = null; return false; } } }
You could off course choose to lose the type-safety and go with a DynamicObject like I showed and then drop the duck-casting.
I made a transparant extendible version of this object proxy, and opensourced it here.
https://github.com/Curit/DynamicProxy
作者:Chuck Lu GitHub |
分类:
Castle
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-05-20 Create an ASP.NET Core web app in Visual Studio Code
2017-05-20 CSS元素选择器 element selector(type selector)
2017-05-20 如何查看本机正在监听的端口
2017-05-20 Error 0x80070020 when you try to start a Web site in IIS 7.0